具有 2 个值的哈希图 java
Hash map with 2 values java
我需要一个 HashMap,它看起来像
Map<String, int,ArrayList<String>> table = new HashMap<String, int,ArrayList<String>>( );
但是 HashMap 只接受一个映射值。
我试着用一些包装的 class 来实现这个,看起来像
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>
,它指定:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
因此,无论您如何划分,您都无法真正拥有 "two" 个值。
但是,您似乎不需要两个值,而是两个键。当您指定一个 String 和 一个 int 时,您期望 return 中的 ArrayList。如果是这种情况,Sachin 的 Map<String, HashMap<Integer,ArrayList<String>>>
建议就可以了。您还可以制作一个 class 来更好地处理嵌套地图:
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
我需要一个 HashMap,它看起来像
Map<String, int,ArrayList<String>> table = new HashMap<String, int,ArrayList<String>>( );
但是 HashMap 只接受一个映射值。
我试着用一些包装的 class 来实现这个,看起来像
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>
,它指定:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
因此,无论您如何划分,您都无法真正拥有 "two" 个值。
但是,您似乎不需要两个值,而是两个键。当您指定一个 String 和 一个 int 时,您期望 return 中的 ArrayList。如果是这种情况,Sachin 的 Map<String, HashMap<Integer,ArrayList<String>>>
建议就可以了。您还可以制作一个 class 来更好地处理嵌套地图:
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