我有一个类,它在一个列表中保存一个列表,它被声明为 String 类型,但我不再知道它是一个字符串。
private ArrayList<List<String>> table;
table = new ArrayList<List<String>>();
table.add(new ArrayList<String>()); //is possible
table.add(new ArrayList<Integer>()); //not possible
但现在嵌套列表可以是字符串或整数。我该如何解决?我也不能声明对象必须是字符串或整数
单个 Arraylist 也可以在不声明为对象的情况下同时包含整数和字符串吗?
编辑:看来你们正在讨论正确答案。我会明白为什么我选择 Vikdor 答案。
我的工作是加载一个 csv,然后用户输入命令将每一列定义为字符串或整数。我的表类有一个私有(private)实例变量,并且有添加值的方法。以 Vikdor 的方式进行操作使得在我想合并两个表或排序的表上执行操作变得非常容易。它还将阻止用户通过异常输入非字符串或 int。
最佳答案
您可能正在寻找这个:
List<List<? extends Object>> table;
table = new ArrayList<List<? extends Object>>();
table.add(new ArrayList<String>());
table.add(new ArrayList<Integer>());
当您检索内部列表时,这将导致未经检查的代码,如下所示(在生产代码中显然不推荐这样做):
List<String> stringList = (List<String>) table.get(0); // Unchecked cast.
来自 OP 的评论:
Because its my requirement to have it as either int or string. Else you can put more than those types in the list. The nested list holds value of a table in columns and each column holds int or string. Do you have any other dynamic way of reading csv file and storing in table?
最好使用适当的 CSV 处理器(如 SuperCSV ),它可以直接解析为 POJO,每个列都有适当的数据类型。
关于java - 未知数据类型声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13206018/