What is the best way to store three attributes entry sets in Java?
HashMaps allow for mapping key value pairs; what is the recommendation if there is an extra value?
i.e HashMap maps key-valu开发者_Go百科e pairs: Key, Value
What is the best way to map: Key, Value, Value1?
Thanks.
A nice, clean solution I like is to write up a utility class that matches a pair:
public class Pair<U, V> {
private U first;
private V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
// getters for "first" and "second"
and then have that be the Value
in your map:
Map<Key, Pair<U,V>> map;
However, this would be in the case that you would always have only two values. If you have a feeling that there might be more in the future, a List<Object>
or Set<Object>
will be better to use as a Value
in the map.
EDIT you could have a static creator-method too:
public static <U, V> Pair<U, V> newInstance(U first, V second) {
return new Pair<U, V>(first, second);
}
The standard solution is to encapsulate the two values in their own data structure.
The data structure could be specific to your situation, or you could hack together a simple Pair
class.
You'd then use an instance of the structure as your list value, e.g. map.put(key, new Pair(foo, bar));
There's also the option of using a specialised Map
implementation, e.g. http://commons.apache.org/collections/api-3.1/org/apache/commons/collections/MultiMap.html
You can :
Use a list as value
Map<String,List<String>> map = new HashMap<String,List<String>>(); map.put("key",Arrays.asList("one","two" ); map.get("key").get(0); map.get("key").get(1);
Use an array as value and refer as
Map<String,String[]> map = new HashMap<String,String[]>(); map.put( "key", new String[]{"one", "two"}); map.get("key")[0]; map.get("key")[1];
Use a custom generic class to hold two values
Map<String,Pair> map = new HashMap<String,Pair>(); map.put( "key", new Pair<String,String>("one","two")); map.get("key").val1(); map.get("key").val2();
You can use Map< key,List< MyVOClazz > >
public class MyVOClazz{
private String value1;
private String value2;
//getters, setters for value1 and value2
}
精彩评论