我写了下面的代码,有两个String对象,但是在HashSet
或HashMap
中只添加了一个String:
String s1 = new String("Text");
String s2 = "Text";
//checking with Reference equality operator
System.out.println("Does both are same object: " + s1 == s2);
//not equal two different object of String is created
HashSet<String> set = new HashSet<>();
set.add(s1);
set.add(s2);
for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
String strObj = (String) iterator.next();
System.out.println(strObj);
}
输出是:
文本
我知道在 HashMap
或 HashSet
中添加任何对象取决于 equal()
方法:即对于 String
s1.equals(s2) //returns true
这就是为什么在 HashMap
或 HashSet
(在契约(Contract)中)中只添加了一个 String 的原因,但是解决方法是什么我想将两个 String 添加为它们是不同的对象。
String
是一个 final
类,因此我无法创建子类并覆盖 equals()
和 hashCode()
使用引用相等运算符检查并返回 true 或 false 的方法。
最佳答案
我想你想要的是 IdentityHashMap 。此类按标识(即使用 ==
)而不是按相等(即使用 equals
)比较对象。
因为没有 IdentityHashSet
类,如果您想要一个具有与 IdentityHashMap
相同特征的 Set
,您可以只使用 Collections.newSetFromMap
实用程序方法。此实用程序方法只是在给定的 Map
周围创建一个包装器,使其看起来像一个 Set
。例如:
Set<String> myIdentitySet = Collections.newSetFromMap(new IdentityHashMap<String,Boolean>());
关于java - 如何在 HashMap/HashSet 中存储两个相等的字符串或任何对象(具有不同的引用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22721385/