Java question about ArrayList<Integer>[] x

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

I have always had this one issue with arrays of ArrayLists. Maybe you can help.

//declare in class private ArrayList<Integer>[] x;  //in constructor x=new ArrayList[n]; 

This generates a warning about unchecked conversion.

But

x=new ArrayList<Integer>[n]; 

is a compiler error.

Any idea?

Thanks!

回答1:

You can't make a array of generics lists. Fortunately, there are workarounds. And even more fortunately, there is a nice site about Generics with more information than you'd ever want to know. The link goes straight to the Arrays in Java Generics part.



回答2:

I think you cannot make array of generic arraylist because no generic information will be available at runtime.Instead you can do like this:

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); 


回答4:

Run the flowing code:

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());         }      }  } 

You will get:

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

Because Java don't support generic array. When you declare:

private ArrayList<Integer>[] x; 

The compiler will think it is :

private ArrayList[] x; 

So, you should do like that:

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


回答5:

It shouldn't have been an error. A warning is enough. If nobody can create an ArrayList<Integer>[], there is really no point to allow the type.

Since javac doesn't do us the favor, we can create the array ourselves:

@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 constraint isn't perfect, caller should make sure the exact class is passed in. The good news is if a wrong class is passed in, a runtime error occurs immediately when assigning the result to x, so it's fail fast.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!