0

i'm currently trying to use generic lists to use different datatypes (int,double,string etc.) for one constructor class. I'm running into problems when it's trying to create the array. I'm using following code:

import java.lang.reflect.Array;

public class SimpleArrayList<ListedType> extends entrance {
      private int length;
      private int grow;
      private ListedType[] buffer;


    @SuppressWarnings("unchecked")
    public SimpleArrayList(int InitialLength,int grow){
        length= 0;
        this.grow = grow;
        buffer = (ListedType[])Array.newInstance(getClass().getComponentType(),InitialLength);
    }

using following testing ground:

public class entrance {

    public static void main(String[] args) {
        SimpleArrayList<?> A = new SimpleArrayList<Integer>(10,1);

        for (int i=0; i<=A.getLength()-1; i++)
        System.out.print(A.getAt(i)+ ", ");
    }

}

can somebody help me please?

1 Answer 1

3

The problem is your call to getClass().getComponentType(). The getClass() method will return SimpleArrayList.class, and then getComponentType() will return null, because SimpleArrayList isn't an array.

Short example of that:

public class Test {    
    public static void main(String[] args) {
        new Foo<String>().printComponentType();
    }
}

class Foo<T> {
    public void printComponentType() {
        System.out.println(getClass().getComponentType()); // null
    }
}

Array.newInstance throws a NullPointerException if you pass null as the first argument.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.