Does Map in Java allow duplicate elements?

  • 2021-06-29 10:59:14
  • OfStack

There are three common collection interfaces in Java: List, Set, Map. It is known that duplicate elements are allowed in List, but not in Set. Is duplicate elements allowed in Map?

Looking at the data, we found that map is out of order and its query needs to be searched by the value of key. If you define two identical keys, one key corresponds to more than one value, which violates java's definition of map, where the key and value correspond to 11.Therefore, key cannot be repeated.

Write a code test 1:


package com.test.collection;
import java.util.HashMap;
import java.util.Map;
//Map in key Tests with non-repeatable values 
public class TestEquals {
  public static void main(String[] args) {
    String s1=new String("abc");
    String s2=new String("abc");
    Map map=new HashMap();
    map.put(s1, "abc123");
    map.put(s2, "ABC456");// No. 2 Will override the 1 Elements 
    // Be careful: map in key Values are not repeatable and are compared directly against equals, only equals Same Overlay 
    System.out.println(map.size());
    System.out.println(map.get(s1));
  }
}

Output results:

1
ABC456

If key is duplicated, which value of this key should be selected to put in the container?Do a test:


public class Test {
  public static Map putSome(Map<String,String> map){
    map.put("gender", "Male");
    map.put("name", "Athor");
    map.put("name", "Cindy");
    map.put("name", "Billy");
    map.put("from","China");
    return map;
  }
  public static void main(String[] args) {
    System.out.println(putSome(new HashMap<String,String>()));
    System.out.println(putSome(new TreeMap<String,String>()));
    System.out.println(putSome(new LinkedHashMap<String,String>()));
  }
}

Output results:

{name=Billy, gender=Male, from=China}
{from=China, gender=Male, name=Billy}
{gender=Male, name=Billy, from=China}

It can be seen that no matter which subclass of Map, the value corresponding to the key name is Billy, that is, the last key-value pair of name, which overrides the previous name key-value pair.

summary


Related articles: