Vis*_*ant 1 java collections equals hashmap hashset
我已经写了下面的代码,有两个String对象,但只有一个字符串添加在HashSet或HashMap:
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);
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Text
我知道添加任何对象HashMap或HashSet取决于equal()方法:即两个字符串
s1.equals(s2) //returns true
Run Code Online (Sandbox Code Playgroud)
这就是为什么只添加一个String HashMap或者HashSet(在合同中)的原因,但是我想要添加两个String的解决方法是什么,因为它们是不同的对象.
String是一个final类所以我不能创建子类和覆盖equals()和hashCode()方法来检查引用相等运算符并返回true或false.
我想你想要的是IdentityHashMap.此类按标识(即使用==)而不是通过相等(即使用equals)来比较对象.
由于没有IdentityHashSet类,如果你想要一个Set具有相同特性的IdentityHashMap你可以只使用Collections.newSetFromMap实用方法.这个实用程序方法只是在给定的周围创建一个包装器Map,使其看起来像一个Set.例如:
Set<String> myIdentitySet = Collections.newSetFromMap(new IdentityHashMap<String,Boolean>());
Run Code Online (Sandbox Code Playgroud)