Resize Array

If it were a regular array, I could just create a new array and then make arraycopy, but generics will not let me do this. The best I've come up with so far:

public void resize() {
    T[] tempArray = Arrays.copyOf(myArray,myArray.length*3);
}

It compiles, but at runtime I get a null pointer exception. Can someone explain what I'm doing wrong?

+5
source share
2 answers

you can use Arrays.copyOf(myArray,myArray.length*3)to make a copy

I assume it myArray[0]is null, so it myArray[0].getClass()throws a nullpointer

if you need a runtime type you can use myArray.getClass().getComponentType()

+6
source

Two things:

  • resize(), , , myArray[0]. , getClass() .

  • , myArray = tempArray, , , ArrayIndexOutOfBounds.

0

All Articles