将java.util.Date存储为基于引用相等而不是"值"相等的Map中的键

Aer*_*yes 2 java collections dictionary date

我想构建一个Date对象的HashMap,所以每当我有两个不同的Date对象具有相同的Date值(day,month,year,..)时,Hashmap不会用新的值替换过去的值.

例:

    Date x = new Date();
    Date y = new Date();

    HashMap<Date,Integer> hm = new HashMap<Date,Integer>();
    hm.put(x,1);
    hm.put(y,3);

    System.out.println(hm.get(x));
    System.out.println(hm.get(y));
Run Code Online (Sandbox Code Playgroud)

在这个例子中,他们都打印3.我想确保他们打印1然后3.

我已经考虑过将键值放在Hashmap中作为每个日期的对象引用(因为它们会有所不同),那么如何强制执行该对象呢?

或者有更好的方法吗?

Gáb*_*kos 5

您应该使用java.util.IdentityHashMap执行此任务.这样你可以拥有equals,但你的不同对象Map.

编辑:你的例子:

Date x = new Date();
Date y = new Date();

Map<Date,Integer> hm = new IndentityHashMap<Date,Integer>();
hm.put(x,1);
hm.put(y,3);
assert hm.size() == 2: hm.size();
Run Code Online (Sandbox Code Playgroud)

正如@BoristheSpider所指出的,当您丢失原始对象的引用时,这可能不是最好的数据结构.在这种情况下MultiMap(如番石榴的)或ListEntryS/PairS/TupleS可能会发生是一个更好的根据使用情况选择.(前者适用于您希望所有值都属于某些equals键的情况,后者是访问所有键/值对,但不是按键搜索.)

如果您只想将Map某个或所有(存储的)密钥用作随机访问的"数组",那么这IdentityHashMap是一个不错的选择.

  • @AerRayes注意,如果丢失原始引用,你可以**永远不会从`IdentityHashMap`中检索`Object`. (3认同)