现在是有一个一多对应的映射.........如何通过hashmap去将所有的映射都对应起来呢例如
key value
 a    1
 a    2
 a    3然后的话,怎么去得到 a 所对应的所有值呢???????另外的话,map的对象模型是怎么样的呢?
例如:
hashMap a = new hashMap();
a.put("one","1");
a.put("one","2");
a.put("one","3");然后我再
a.put("two","4");
a.put("two","5");
a.put("two","6");
这样的话,可以再找到one的映射吗?
刚开始学习map对map的操作不是很熟悉,求前辈指点

解决方案 »

  1.   

    Map的key必须是唯一的,如果使用同一个key,调用两次put方法,那么第二个值将取代第一个值
    就像下面这样:
    import java.util.*;public class Test1 {
    public static void main(String[] args) {
    HashMap<String, String> a = new HashMap<String, String>();
    a.put("one", "1");
    a.put("one", "2");
    a.put("one", "3");
    a.put("two", "4");
    a.put("two", "5");
    a.put("two", "6");
    Set<Map.Entry<String, String>> s = a.entrySet();
    Iterator<Map.Entry<String, String>> it = s.iterator();
    while (it.hasNext()) {
    System.out.println(it.next());
    } }}如果需要一个a对应多个值,那么把这些值放到集合里,然后再放到Map里不就可以了?
      

  2.   

    key 是钥匙只能对应一个锁 value,也就是说 key 是不能重复的,像你的例子中实际上只存进去两个:one --> 3 和 two --> 6,键是一样的话,后面 put 进去的值会将前的已经存在其中的值给冲掉。如果要实现 one 对应 1、2、3 的话,可以使用 key 是 String 类型,而 value 为 List 类型就可以了,参考代码:import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;public class Test {  public static void main(String[] args) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();    List<String> one = new ArrayList<String>();
        one.add("1");
        one.add("2");
        one.add("3");    List<String> two = new ArrayList<String>();
        two.add("4");
        two.add("5");
        two.add("6");
        
        map.put("one", one);
        map.put("two", two);    // 通过 foreach 循环输出
        // 遍历 map
        for(Map.Entry<String, List<String>> entry : map.entrySet()) {
          // 遍历 map 中 value 的 List
          for(String str : entry.getValue()) {
            System.out.println(entry.getKey() + " --> " + str);
          }
        }
      }
    }
      

  3.   

    ls都已经说了,对于map的key必须是唯一的
      

  4.   

    一把钥匙开一把锁 
    key要唯一 value 只有是对象就行 例如:集合 数组 字符串等
    Collection collection=map.values(); 返回值集合
    Set set = map.keySet();返回键结合
    注意: set 集合是不允许重复值的 这就反向说明key要唯一