0

为什么我在 if 语句中出现错误,我该怎么做才能找到嵌套数组列表可以容纳的数据类型?

ArrayList<List<? extends Object>> table;
table = new ArrayList<List<? extends Object>>();
table.add(new ArrayList<String>());
if( table.get(0) instanceof List<String> ){
//Do something
}
4

2 回答 2

3

作为替代方案,您可以为 String 和 Integer 创建 ArrayList 的两个子类,并检查它们:

public class StringList extends ArrayList<String> {
   //Add needed constructors here
}

public class IntegerList extends ArrayList<Integer> {
   //Add needed constructors here
}

然后,您可以执行以下操作:

ArrayList<List<? extends Object>> table;
table = new ArrayList<List<? extends Object>>();
table.add(new StringList());
if( table.get(0) instanceof StringList ){
//Do something
}
于 2012-11-04T19:20:15.063 回答
2

您不能instanceof与泛型类型一起使用。泛型类型在运行时被擦除。

于 2012-11-04T18:47:10.777 回答