Java,在多维数组中存储混合数据类型的最简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5809486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java, easiest way to store mixed-data types in a multidimensional array?
提问by James
Ive got a file with some String and ints I wish to store in a 2D 'array'. What is the best way of doing this? I havent done Java for a while and i've been using VBA (where you have no datatypes), so i'm a little bit rusty.
我有一个包含一些字符串和整数的文件,我希望将其存储在二维“数组”中。这样做的最佳方法是什么?我有一段时间没有使用 Java,而且我一直在使用 VBA(您没有数据类型),所以我有点生疏。
回答by Edwin Buck
Make it a two dimensional array of Objects, if you must.
如果必须,请将其设为对象的二维数组。
A better solution is to find a common interface, and make it a two dimensional array of that interface.
更好的解决方案是找到一个通用接口,并将其设为该接口的二维数组。
The best solution is to do something like
最好的解决方案是做类似的事情
public class Entry {
private String name;
private int value;
public Entry(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
}
And make it a single dimensional array of Entry
s. Note that if you really wanted to "go for the gold" rename the above Entry
class to a class name that actually makes sense.
并使其成为Entry
s 的一维数组。请注意,如果您真的想“全力以赴”,请将上述Entry
类重命名为真正有意义的类名。
回答by nfechner
If the strings and the integers are in any relation, maybe a map might help you. Example, if you have strings, that map to integers (int and Integer can be easily converted. Read up on autoboxing):
如果字符串和整数之间存在任何关系,那么地图可能会对您有所帮助。例如,如果您有字符串,则映射到整数(int 和 Integer 可以轻松转换。阅读自动装箱):
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Teststring", 5);
This would be for a lookup list, where order is not important. If you need ordering, use for example a TreeMap.
这将用于查找列表,其中顺序并不重要。如果您需要订购,请使用例如 TreeMap。
Also you should check out Apache Commons IO, which is a free library that can be a huge help in handling files. (Like almost everything in Apache Commons. These libraries have saved my sanity/job/life more than once...)
此外,您应该查看Apache Commons IO,这是一个免费库,可以在处理文件方面提供巨大帮助。(就像 Apache Commons 中的几乎所有东西一样。这些库不止一次挽救了我的理智/工作/生活......)