是否有可能实现一个HashMap有一个键和两个值。就像HashMap?

请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?


当前回答

HashMap<Integer,ArrayList<String>> map = new    HashMap<Integer,ArrayList<String>>();

ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
map.put(100,list);

其他回答

HashMap<Integer,ArrayList<String>> map = new    HashMap<Integer,ArrayList<String>>();

ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
map.put(100,list);

另一个不错的选择是使用Apache Commons中的MultiValuedMap。查看页面顶部的所有已知实现类,了解专门的实现。

例子:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

可以用

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

So,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

将导致集合coll中包含“A”、“B”和“C”。

我更喜欢下面的方法来存储任意数量的变量,而不必创建一个单独的类。

final public static Map<String, Map<String, Float>> myMap    = new HashMap<String, Map<String, Float>>();

你可以隐式地做。

// Create the map. There is no restriction to the size that the array String can have
HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();

//initialize a key chosing the array of String you want for your values
map.put(1, new String[] { "name1", "name2" });

//edit value of a key
map.get(1)[0] = "othername";

这是非常简单和有效的。 如果你想要不同类的值,你可以这样做:

HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();
 import java.io.*;
 import java.util.*;

 import com.google.common.collect.*;

 class finTech{
public static void main(String args[]){
       Multimap<String, String> multimap = ArrayListMultimap.create();
       multimap.put("1","11");
       multimap.put("1","14");
       multimap.put("1","12");
       multimap.put("1","13");
       multimap.put("11","111");
       multimap.put("12","121");
        System.out.println(multimap);
        System.out.println(multimap.get("11"));
   }                                                                                            
 }                                                                    

输出:

     {"1"=["11","12","13","14"],"11"=["111"],"12"=["121"]}

      ["111"]

这是用于实用功能的Google-Guava库。这就是需要的解决方案。