为什么我在 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
}
为什么我在 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
}
作为替代方案,您可以为 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
}
您不能instanceof
与泛型类型一起使用。泛型类型在运行时被擦除。