java - 未知数据类型声明

标签 java string integer declaration

我有一个类,它在一个列表中保存一个列表,它被声明为 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/

相关文章:

java - java中双变量出现的百分之一

java - 各种搜索算法的Big-O运行时间

java - 检查Java中是否加载了包(API)

string - 在 Rust 中将 Vec<String> 转换为 &str 的一部分?

c# - Linq 查询从多个 List<string> 中选择单个字符串

Java:将最后一位数字与 INT 的其余部分分开

c++ - 接受整数或字符串的方法。 C++

java - Java Eclipse NEON 空指针异常

python - 当作为参数传递给 range() 时,如何告诉 PyCharm 类实例可以通过 __index__ 方法解释为整数?

c++ - 在 C++ 中读取大字符串——有安全快速的方法吗?