Java 储存相同 key 的 map

Java About 1,220 words

IdentityHashMap

  • 判断的是==equals的区别;
    • 如果put的是"abc",那么key会覆盖。
    • 如果put的是new String("abc"),则不会覆盖。
  • ==判断的是intfloat等基础类型的值是否相等,equals判断的是地址值是否相等;
  • HashMap判断的是hashCode()equals()是否相等,复写了这两个方法的,则认为是重复key;
  • IdentityHashMap判断的是地址值是否相等,如果是new的对象,地址值都不同;
@Data
public class TestMap {
    private String a;
    private String b;
}

@Test
public void testIdentityHashMap() {
    Map<TestMap, String> identityHashMap = new IdentityHashMap<>();
    TestMap testMap1 = new TestMap();
    testMap1.setA("a");
    testMap1.setB("b");

    TestMap testMap2 = new TestMap();
    testMap2.setA("a");
    testMap2.setB("b");

    identityHashMap.put(testMap1, "testMap1");
    identityHashMap.put(testMap2, "testMap2");
    System.out.println(identityHashMap.toString());

    Map<TestMap, String> hashMap = new HashMap<>();
    hashMap.put(testMap1, "testMap1");
    hashMap.put(testMap2, "testMap2");
    System.out.println(hashMap.toString());


    Map<String, String> map = new HashMap<>();
    map.put(new String("1"), "123");
    map.put(new String("1"), "456");
    System.out.println(map.toString());
}

输出:

{TestMap(a=a, b=b)=testMap1, TestMap(a=a, b=b)=testMap2}
{TestMap(a=a, b=b)=testMap2}
{1=456}
Views: 3,553 · Posted: 2019-04-08

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh