【问题标题】:instanceof in java on a nested array listjava中的instanceof在嵌套数组列表上
【发布时间】:2012-11-04 18:44:48
【问题描述】:

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
}

【问题讨论】:

    标签: java string arraylist instanceof


    【解决方案1】:

    作为替代方案,您可以为 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
    }
    

    【讨论】:

    • 很遗憾,您不能同时接受这两个答案,因为它们确实提供了回答此问题所需的所有信息。
    【解决方案2】:

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

    【讨论】:

    • 更清楚地说,你不能像你想要做的那样做任何事情。鉴于您提供的代码,table.get(0) 是一个空的 ArrayList,并且对于它可能应该具有的元素类型一无所知
    • 在数组列表中添加字符串或整数之前,我是否需要知道任何替代方法
    • 替代方案是首先不要将您的程序设计为混合不同类型的ArrayLists。有你的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2012-06-03
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多