简体   繁体   中英

How do I create a new AnyType array

I am using the code from the answer How do I create a new AnyType[] array? . My question is how to initialize this array. When I try to run this code, I get a null pointer exception on Clear(), which I think is due to using theItems.getClass since theItems haven't been declared already.

public class Whatever<AnyType extends Comparable<? super AnyType>>  extends AbstractCollection<AnyType> implements List<AnyType> {

private static final int DEFAULT_CAPACITY = 10;
private static final int NOT_FOUND = -1;

private AnyType[] theItems;
private int theSize;
private int modCount = 0;


public Whatever() {
    clear();
}

/**
 * Change the size of this collection to zero.
 */
public void clear() {
    theSize = 0;
    theItems = (AnyType[]) java.lang.reflect.Array.newInstance(theItems.getClass().getComponentType(), DEFAULT_CAPACITY);
    modCount++;
}
}

So I found two ways I could accomplish this. The first, using Jack's comment from above, looks like:

public static <T> T[] alloc(int length, T ... base) {
    return Arrays.copyOf( base, length );
}

It can then be called like:

theItems = ClassName.alloc(DEFAULT_CAPACITY);

The way I ended up using could be used because I implemented comparable:

theItems = (AnyType []) new Comparable[ DEFAULT_CAPACITY ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM