在Eclipse里有如下语句List<String>[] list = new List[5];等号右边出现黄色波浪线,说
Type safety:The expression of type List[] needs unchecked conversion to conform to List<String>[]
不太明白是什么意思,怎样改才能去掉这样警告呢?
Type safety:The expression of type List[] needs unchecked conversion to conform to List<String>[]
不太明白是什么意思,怎样改才能去掉这样警告呢?
不对啊,这回是红叉叉了。Cannot create a generic array of List<String>
你可以这样:
List <List<String>>list = new ArrayList<List<String>>();
不就解决了?
@SuppressWarnings("unchecked")
就ok了,就会经类型安全问题的警告(黄线)取消了。
T[] t = (T[])new Object[size];就是强制把那个T 转成Object的类型我可能说错了 谁纠正下。。
In a little more detail:
The Java designers decided to disallow arrays of generics because 1) it would not be type-safe, and 2) generics were added to the language precisely to ensure type-safety.Arrays are also not type-safe:String[] strings;
Object[] objects = strings; // allowed because of covariance
objects[0] = Long.valueOf(9); // fails at runtime with ArrayStoreExceptionBecause generic types don't carry the type parameter at runtime (that info is "erased"), the JVM cannot even throw an ArrayStoreException in this exampleList<String>[] stringsArray = ... // can't create
Object[] objects = stringsArray; // allowed because of covariance of arrays
List<Long> longs = Arrays.asList(Long.valueOf(7));
objects[0] = longs; // ArrayStoreException cannot be thrown because JVM doesn't know the type parameter Long, it's been erased
int length = stringsArray[0].get(0).length(); // would throw ClassCastException---type safety compromised
http://topic.csdn.net/u/20090309/14/64e0e298-9cfd-4e49-8e6e-71125839a4f3.html
要多写一点代码。
for(int i=0;i<list.length;i++){
list[i]=new ArrayList();
}
for(int j=0;j<5;j++){
if('condition'){
list[j].add('String');
}
}如果用列表好像不怎么好实现。
List[] list = new List[pars.length];
for(int i=0; i<list.length; i++) {
list[i] = new ArrayList();
}for(int i=0; i<testList.size(); i++) { //这里的testList保存了很多数据,并且是List<Object[]>型的
Object[] ob = (Object[]) testList.get(i);
String type = ob[0].toString().trim();
String par = ob[4].toString().trim();//只需要这个两个数据
if(testMap.get(type)!=null) {
for(int j=0; j<pars.length; j++) {
if(par.equals(pars[j])) {
list[j].add(type);
}
}
}
}就是这样初始化的。如果用List<List<String>>,还不知道如何实现。
public synchronized <T> T[] toArray(T[] a) {
if (a.length < elementCount)
return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass()); System.arraycopy(elementData, 0, a, 0, elementCount); if (a.length > elementCount)
a[elementCount] = null; return a;
}
自己体会