我需要创建一个记录两列{int,String}的List。我认为ArrayList是我需要的,但我无法理解它。我从数据库中提取了字符串,而int是我需要识别字符串位置的索引值。
List<List<String>> strArray = ArrayList<List<String>>;
然后我可以为我从数据库中提取的每一行执行类似strArray.add()。add()的操作吗?
答案 0 :(得分:15)
如果您的HashMap
值唯一,我认为您应该使用int
String
作为关键字int
作为值。
Map<Integer,String> myMap = new HashMap<Integer,String>();
myMap.put(1,"ABC");
请注意,由于Map
是集合而java集合不存储int
之类的原语,因此它们存储对象,因此您必须为Integer
使用int
包装类值。
请参阅此链接Why can Java Collections not directly store Primitives types?
答案 1 :(得分:15)
另一种方法是制作自定义对象:
Class CustomObject {
int value1;
String value2;
CustomObject(int v1, String v2) {
value1 = v1;
value2 = v2;
}
}
然后使用它:
List<CustomObject> myList = new ArrayList<CustomObject>();
CustomObject o1 = new CustomObject(1, "one");
myList.add(o1);
// etc.
如果int
值是唯一的,并且您想要考虑它们,那么Map
可以像其他人建议的那样工作。
答案 2 :(得分:4)
如果您只需要两个值,则可以使用原生Pair类
List<Pair> mPairs = new ArrayList<Pair>();
Pair pair = new Pair(123,"your string");
mPairs.add(pair);
如果你的int值不是唯一的,那么这将是一个很好的决定,所以你不能使用HashMap
答案 3 :(得分:1)
如果您的ID不是唯一的,您仍然可以使用地图:
Map<Integer, String> map = new IdentityHashMap<Integer, String>();
map.put(new Integer(1), "string");
IdentityHashMap - 为每个OBJECT使用本机hashCode实现,因此您不需要唯一的ID,但您必须通过运算符'new'创建所有整数,并且不要使用自动装箱,因为有一些cache mechanism 。
还有JVM参数,它控制缓存大小'-XX:AutoBoxCacheMax ='。 但是使用此参数无法禁用缓存,如果将size设置为零,则缓存将忽略它并使用默认值:[ - 122; 127]。 此参数仅适用于整数,Long没有这种参数。
<强>更新强> 对于非唯一键,您可以使用某种多重映射: 地图&GT;图
使用非唯一键存储您的值:
map.put(1, new ArrayList<String>());
map.get(1).add("value1");
map.get(1).add("value2");
例如,你可以使用HashMap。
你也可以在google-collections中找到MultiMap实现:'guava'。
答案 4 :(得分:0)
我认为你可以将int和string包装在一个类中,然后将类对象放在List中。
答案 5 :(得分:0)
Map是一个将键映射到值的对象。地图不能包含重复的键;每个键最多可以映射一个值。
我认为如果您使用Map<Integer,String>
会更好,key(Integer)
将成为指向String
值的索引。
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"str1");
map.put(2,"str2");
...