HashMap以List作为Key值存在的问题
//Test1
		List<String> list1 = new ArrayList<String>();
		list1.add("Elem1");
		list1.add("Elem2");
		Map<List<String>, String> map = new HashMap<List<String>, String>();
		map.put(list1, "Can get value.");
		System.out.println("Elements of list1: "+list1);
		List<String> list2 = new ArrayList<String>();
		list2.add("Elem1");
		list2.add("Elem2");
		System.out.println("Elements of list2: "+list1);
		System.out.println("Test1. Get value from HashMap(Key: list1) by the key list2: "+map.get(list2)+"\n");
		
		//Test2
		list1 = new ArrayList<String>();
		list1.add("Elem1");
		map = new HashMap<List<String>, String>();
		map.put(list1, "Can get value.");//list1 only one element, and it's hash code is 67040897
		list1.add("Elem2");//Add one element, even though ArrayList is a kinds of reference type, but map keys' hash code not change.
		System.out.println("Elements of list1: "+list1);
		list2 = new ArrayList<String>();
		list2.add("Elem1");
		list2.add("Elem2");
		System.out.println("Elements of list2: "+list2);
		System.out.println("Test2. Get value from HashMap(Key: list1) by the key list2: "+map.get(list2)+"\n");
		
		//Test3
		list1 = new ArrayList<String>();
		list1.add("Elem1");
		map = new HashMap<List<String>, String>();
		map.put(list1, "Can get value.");
		list1.add("Elem2");
		System.out.println("Elements of list1: "+list1);
		Map<List<String>, String> tempMap = new HashMap<List<String>, String>();
		tempMap.putAll(map);//Will be recalculate the keys' hash code
		list2 = new ArrayList<String>();
		list2.add("Elem1");
		list2.add("Elem2");
		System.out.println("Elements of list2: "+list2);
		System.out.println("Test3. Get value from HashMap(Key: list1) by the key list2: "+tempMap.get(list2));
 
                    
                
                
            
        
浙公网安备 33010602011771号