[Java SE] The pits stepped on by the Map collection~


Map element added~

package Review;

import java.util.HashMap;
import java.util.Map;

public class MapTest {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		
	    // 1.创建一个Map集合
		Map<String, String> hashMap = new HashMap<String, String>();
	    // 2.添加元素
		hashMap.put("1", "嘿嘿");
		hashMap.put("1", "哈哈");
		hashMap.put("1", "呵呵");
		// 3. 测试
		System.out.println("输出结果为:"+hashMap.get("1"));
		
	}

}
package Review;

import java.util.HashMap;
import java.util.Map;

public class MapTest {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		
		// 1.创建一个Map集合
		Map<Object, String> hashMap = new HashMap<Object, String>();
	    // 2.添加元素
		hashMap.put(1, "嘿嘿");
		hashMap.put("1", "哈哈");
		hashMap.put(1, "呵呵");
		// 3. 测试
		System.out.println("输出结果1为:"+hashMap.get("1"));
		System.out.println("输出结果2为:"+hashMap.get(1));
		
	}

}

There are the above two pieces of code test, what are the output results?

As we all know, the characteristics of the Map collection:

  • Able to store unique column data (unique, non-repeatable) set
  • Ability to store repeatable data (repeatable) list
  • The order of the values ​​depends on the order of the keys
  • Both keys and values ​​can store null elements
  • A map cannot contain duplicate keys, and each key can only map one value at most

Most of the claims are:When the keys are the same, the Map collection will cover the added elements. But this is a prerequisite:

  • 1.当key的类型相同
  • 2.且加入的key值相同时

Take the above case as an example, the Map collection generics in the first piece of code <k,v>are all Stringtypes, and then three elements with K values ​​of "1" but different Value values ​​are added to the collection in turn. According to what I said before, here are of type String key, and the same key value, the result will be the first code sequence covering, the result is the final output: 呵呵.

Looking at the second code, there are several changes compared to the first code:1. The key generic definition of the Map collection is Object type2. There are two key values ​​when adding elements, namely 1, "1". That is to say, the key value at this time can be any type of data. If it is generally understood 1, is “1”n't it all the same? Simply think that the cover operation is still carried out, and the result is still "ha ha". But after running, I was dumbfounded 结果1:哈哈,结果2:呵呵! ? As mentioned above, two conditions must be met to cover the operation. In other words, the overwrite operation will only occur during the addition of elements of the same type and the same value.


Guess you like

Origin blog.csdn.net/qq_45797116/article/details/114698822