Java question about ArrayList <Integer> [] x

I always had this problem with ArrayLists arrays. Maybe you can help.

//declare in class
private ArrayList<Integer>[] x;

//in constructor
x=new ArrayList[n];

This generates an unverified conversion warning.

But

x=new ArrayList<Integer>[n];

- compiler error.

Any idea?

Thank!

+5
source share
5 answers

You cannot create an array of generalization lists. Fortunately, there are workarounds. And fortunately, there is a good Generics site with more information than you would like to know. The link goes straight to the array in the Java Generics part.

+5
source

, arraylist, . :

List<Integer>[] arr=new ArrayList[30];
arr[0]=new ArrayList<Integer>();//create new arraylist for every index.
+3
ArrayList<?>[] x;
x=(ArrayList<? extends Integer>[]) new ArrayList<?>[10];
x[0] = new ArrayList(1);
0

:

public class Test {
    ArrayList<Long>[] f0;
    ArrayList<Long> f1;
    ArrayList[] f2;
    public static void main(String[] args) {
        Test t = new Test();
        Field[] fs = t.getClass().getDeclaredFields();
        for(Field f: fs ){
            System.out.println(f.getType().getName());
        }

    }

}

:

[Ljava.util.ArrayList;
java.util.ArrayList
[Ljava.util.ArrayList;

Java . :

private ArrayList<Integer>[] x;

, :

private ArrayList[] x;

, :

int n = 10;
ArrayList<Long>[] f = new ArrayList[n];
for(int i=0;i<n;i++){
    f[i] = new ArrayList<Long>();
}
0

. . ArrayList<Integer>[], .

javac , :

@SuppressWarnings("unchecked")
<E> E[] newArray(Class<?> classE, int length)
{
    return (E[])java.lang.reflect.Array.newInstance(classE, length);
}

void test()
    ArrayList<Integer>[] x;
    x = newArray(ArrayList.class, 10);

The type restriction is not perfect, the caller must make sure that the exact class is passed. The good news is that if an erroneous class is passed, a runtime error occurs immediately when assigning the result x, so it does not work quickly.

0
source

All Articles