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

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


当前回答

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

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

其他回答

 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库。这就是需要的解决方案。

我使用Map<KeyType, Object[]>将多个值与Map中的一个键关联起来。这样,我就可以存储与一个键关联的多个不同类型的值。你必须注意保持正确的插入和从Object[]中检索的顺序。

例子: 考虑一下,我们想要存储Student信息。键是id,而我们想要存储姓名,地址和电子邮件与学生相关联。

       //To make entry into Map
        Map<Integer, String[]> studenMap = new HashMap<Integer, String[]>();
        String[] studentInformationArray = new String[]{"name", "address", "email"};
        int studenId = 1;
        studenMap.put(studenId, studentInformationArray);

        //To retrieve values from Map
        String name = studenMap.get(studenId)[1];
        String address = studenMap.get(studenId)[2];
        String email = studenMap.get(studenId)[3];

是也不是。解决方案是为包含与键对应的2(3或更多)值的值构建一个Wrapper类。

你可以隐式地做。

// 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[]>();

看一看guava库中的Multimap及其实现——HashMultimap

类似于Map的集合,但可以将多个值与单个键关联。如果使用相同的键但不同的值调用put(K, V)两次,则multimap包含从键到两个值的映射。