带有整数键的 Java Map:如何比较键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13952579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Map with Integer keys: How are the keys compared?
提问by Scolytus
I just want to be sure that my code is safeusing Integer
objects as keys. Here's a short example:
我只想确保我的代码使用对象作为键是安全的Integer
。这是一个简短的例子:
Integer int1 = new Integer(1337);
Integer int2 = new Integer(1337);
if (int1 == int2) {
System.out.println("true");
} else {
System.out.println("false");
}
if (int1.equals(int2)) {
System.out.println("true");
} else {
System.out.println("false");
}
Map<Integer, Object> map = new HashMap<Integer, Object>();
map.put(int1, null);
map.put(int2, null);
System.out.println(map.size());
The code will output
代码会输出
false
true
1
That's what I was expecting, the references differ but they equal each other. Now I'm interested in the Map's behavior.
这就是我所期望的,参考文献不同,但它们彼此相等。现在我对 Map 的行为感兴趣。
- Is it guaranteed that Collections like Map or Set will compare the keys by their content and not their reference?
- Or depends it on the actual implementation, like
HashMap
?
- 是否保证像 Map 或 Set 这样的集合会通过它们的内容而不是它们的引用来比较键?
- 或者取决于实际的实现,比如
HashMap
?
回答by gefei
The method equals
is called, hence it's the content that is compared.
该方法equals
被调用,因此它是比较的内容。
As to your two questions above:
至于你上面的两个问题:
Given two objects o1
and o2
(to simplify, we assume that o1!=null
and o2!=null
), a hasp map, ultimately, has to determine if they have the same value. (ultimately, since HaspMap
also checks if o1
and o2
have the same hash value, but this is not important in the context of your question). It does this by calling the method equals()
. As long as o1.equals(o2)
is false, the two objects are considered two different keys by HashMap
.
给定两个对象o1
和o2
(为了简化,我们假设o1!=null
和o2!=null
),搭扣图最终必须确定它们是否具有相同的值。(最终,因为HaspMap
还检查o1
并o2
具有相同的哈希值,但这不是重要的在你的问题的情况下)。它通过调用方法来做到这一点equals()
。只要为o1.equals(o2)
假,这两个对象就被 认为是两个不同的键HashMap
。
HashSet
also calls equals()
to determine if an element is already contained in the set, see http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add%28E%29.
HashSet
还调用equals()
以确定元素是否已包含在集合中,请参阅http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add%28E%29。
TreeMap
, on the other hand, has to compare the two objects, and determine if they are equal, or which one if greater. It does this by calling compareTo()
. Therefore, it is the return value of o1.compareTo(o2)
which is important (or, if you created the tree map with the constructor http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html#TreeMap%28java.util.Comparator%29, the comparator is used).
TreeMap
,另一方面,必须比较两个对象,并确定它们是否相等,或者哪个更大。它通过调用compareTo()
. 因此,它的返回值o1.compareTo(o2)
很重要(或者,如果您使用构造函数http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html#TreeMap %28java.util.Comparator%29,使用比较器)。
What is guaranteed is therefore that in HashMap
and HashSet
, the method equals()
is used to tell objects apart, and in TreeMap
, the method compareTo()
.
因此,可以保证的是,在HashMap
和 中HashSet
,该方法equals()
用于区分对象,而在 中TreeMap
,该方法用于区分对象compareTo()
。
回答by Damian Leszczyński - Vash
Q1: - Is it guaranteed that Collections like Map or Set will compare the keys by their content and not their reference?
Q1: - 是否保证像 Map 或 Set 这样的集合会通过它们的内容而不是它们的引用来比较键?
A1: - No. Collection, Map and Set are interfaces. Only thing that they assure is the contract of possible methods.
A1: - 否。Collection、Map 和 Set 是接口。他们唯一保证的是可能的方法的契约。
Q2: - Depends it on the actual implementation, like HashMap?
Q2: - 取决于实际的实现,比如 HashMap?
A2: Yes. How class deals with comparation it is a developer decision.
A2:是的。类如何处理比较是开发人员的决定。
HashMap use two things to allocate their objects
HashMap 使用两件事来分配它们的对象
First - is Object#hashCode()
, that is used to calculate index.
首先 - 是Object#hashCode()
,用于计算索引。
Second - is Object#equals()
, that is used then hash colision have places.
其次 - 是Object#equals()
,即使用然后散列冲突有地方。
回答by bellum
If you open implementationof java.util.AbstractMap
you can see that keys and values equation is checked using Object#equals
method everywhere. What actually will be compared inside map depends on key/value implementation of Object#equals
method.
如果您打开实现,java.util.AbstractMap
您可以看到使用Object#equals
方法到处检查键和值等式。在 map 中实际比较的内容取决于Object#equals
方法的键/值实现。
回答by NPKR
Here Integer is Waraper final class, which is overriden equals()
method so it will compare only content.
这里 Integer 是 Waraper 最终类,它是重写equals()
方法,因此它只会比较内容。
So If use Integers are Any wrapper class there is no problem in Map
所以如果使用整数是任何包装类,则没有问题 Map
Suppose if You want use Custome Class as key You need override equals() and hashcode()
method to avoid duplicates in Map
假设如果您想使用 Custome Class 作为键,您需要覆盖equals() and hashcode()
方法以避免重复Map
回答by semTex
The first compares two different objects (references) --> false.
第一个比较两个不同的对象(引用)--> false。
The second compares (equal) the values of these objects --> true
第二个比较(相等)这些对象的值 --> true
Hashmap uses the equals and hascode methods of objects to determine unique keys. so you have the same key inserted twice resulting in one remaining element. the second one. have a look at Map#putjavadoc to see whats happening.
Hashmap 使用对象的 equals 和 hascode 方法来确定唯一键。所以你插入了两次相同的键,结果剩下一个元素。第二个。看看Map#putjavadoc 看看发生了什么。
回答by Vallabh Patade
In case of hashmap, keys are compared using equals() and hashcode() methods.
在 hashmap 的情况下,键使用 equals() 和 hashcode() 方法进行比较。
In example above, both hashcode() and equals() and overridden in Integer class. When HashMap compares two keys, first it takes hashcode() of that object and then call equals method on this object and the key having same hashcode value.
在上面的示例中, hashcode() 和 equals() 都在 Integer 类中被覆盖。当 HashMap 比较两个键时,首先获取该对象的 hashcode() ,然后对该对象和具有相同哈希码值的键调用 equals 方法。
回答by Anders R. Bystrup
It actually depend on the equals()
implementation of the K
/key you specify for the Map
.
它实际上取决于equals()
该实施K
指定/键Map
。
Try doing the same with a Map<Object,String>
and see what happens (hint: for Object
's to be equal they actually have to be the same object)
尝试用 a 做同样的Map<Object,String>
事情,看看会发生什么(提示:要使Object
's 相等,它们实际上必须是同一个对象)
Cheers
干杯
回答by Martin A. Kwasowiec
When putting an item inside a HashMap (and HashSet by extension) hashCode is used (transformed by a simple linear function) to determine where the item should be placed inside it's internal collection.
将项目放入 HashMap(以及扩展的 HashSet)中时,使用 hashCode(由简单的线性函数转换)来确定项目应放置在其内部集合中的位置。
Then in the determined location it searches for an identical object (among all items stored there) using (o1 == o2 || o1.equals(o2)), the #equals function is called if references differ, which is a performance improvement to simple #equals call. If identical item is found, its assigned value is replaced with the new one, if not, the new item is simply added to internal collection.
然后在确定的位置,它使用 (o1 == o2 || o1.equals(o2)) 搜索相同的对象(在存储在那里的所有项目中),如果引用不同,则调用 #equals 函数,这是对性能的改进简单的#equals 调用。如果找到相同的项目,则将其分配的值替换为新项目,如果没有,则将新项目简单地添加到内部集合中。