[英]Hash map with 2 values java
我需要一个HashMap一些类似的东西
Map<String, int,ArrayList<String>> table = new HashMap<String, int,ArrayList<String>>( );
但是HashMap仅接受一个映射值。
我试图用一些包装好的类来实现这一点
class Wrapper {
int id;
ArrayList<String> list = new ArrayList<String>();
//Here get and set methods
}
然后我的HashMap看起来像
Map<String, Wrapper> table = new HashMap<String, Wrapper>( );
我需要的是:
当我为HaspMap指定int值时,我应该能够检索该int值的ArrayList。
我怎样才能做到这一点?
首先, HashMap<K,V>
实现Map<K,V>
,它指定:
将键映射到值的对象。 映射不能包含重复的键; 每个键最多可以映射到一个值。
因此,无论如何切片,您都不能真正拥有“两个”值。
但是,似乎您不需要两个值,而是两个键。 当您指定一个String 和一个int时,您期望返回一个ArrayList。 如果是这种情况,Sachin的Map<String, HashMap<Integer,ArrayList<String>>>
将起作用。 您还可以创建一个更好地处理嵌套地图的类:
public class NestedHashMap2<K, L, V> extends HashMap<K, HashMap<L,V>> {
public V put(K k, L l, V v){
if(! containsKey(k)){
put(k, new HashMap<L,V>());
}
return get(k).put(l, v);
}
public V get(K k, L l){
if(! containsKey(k)) return null;
return get(k).get(l);
}
//Expand as needed
}
然后可以将其用作示例:
NestedHashMap2<String,Integer,ArrayList<String>> m = new NestedHashMap2<>();
ArrayList<String> a = new ArrayList<String>();
a.add("Element");
m.put("First",2,a);
ArrayList<String> a2 = m.get("First",2); //--> a2 = a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.