Java question about ArrayList <Integer> [] x
5 answers
:
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