问题描述
我理解 HashSet
是基于 HashMap
实现,但是当您需要独特的元素集时使用。那么为什么在下一个代码中将相同的对象放入地图并设置我们有两个集合的大小等于1?应该不是地图大小是2吗?因为如果两个集合的大小相等,我没有看到使用这两个集合的任何差异。
I understand that HashSet
is based on HashMap
implementation but is used when you need unique set of elements. So why in the next code when putting same objects into the map and set we have size of both collections equals to 1? Shouldn't map size be 2? Because if size of both collection is equal I don't see any difference of using this two collections.
Set testSet = new HashSet<SimpleObject>();
Map testMap = new HashMap<Integer, SimpleObject>();
SimpleObject simpleObject1 = new SimpleObject("Igor", 1);
SimpleObject simplObject2 = new SimpleObject("Igor", 1);
testSet.add(simpleObject1);
testSet.add(simplObject2);
Integer key = new Integer(10);
testMap.put(key, simpleObject1);
testMap.put(key, simplObject2);
System.out.println(testSet.size());
System.out.println(testMap.size());
输出为1和1.
SimpleObject code
public class SimpleObject {
private String dataField1;
private int dataField2;
public SimpleObject(){}
public SimpleObject(String data1, int data2){
this.dataField1 = data1;
this.dataField2 = data2;
}
public String getDataField1() {
return dataField1;
}
public int getDataField2() {
return dataField2;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((dataField1 == null) ? 0 : dataField1.hashCode());
result = prime * result + dataField2;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleObject other = (SimpleObject) obj;
if (dataField1 == null) {
if (other.dataField1 != null)
return false;
} else if (!dataField1.equals(other.dataField1))
return false;
if (dataField2 != other.dataField2)
return false;
return true;
}
}
推荐答案
map保存唯一键。当您使用地图中存在的键调用 put
时,该键下的对象将替换为新对象。因此尺寸为1。
The map holds unique keys. When you invoke put
with a key that exists in the map, the object under that key is replaced with the new object. Hence the size 1.
两者之间的差异应该是显而易见的:
The difference between the two should be obvious:
-
Set
中存储键/值对 - 您只储存键
- in a
Map
you store key-value pairs - in a
Set
you store only the keys
事实上, HashSet
c $ c> HashMap 字段,并且每当调用 add(obj)
时, put
方法在底层映射上被调用 map.put(obj,DUMMY)
- 其中虚拟对象是 private static final Object DUMMY = new Object ()
。因此,地图会填充您的对象作为键,并且不感兴趣的值。
In fact, a HashSet
has a HashMap
field, and whenever add(obj)
is invoked, the put
method is invoked on the underlying map map.put(obj, DUMMY)
- where the dummy object is a private static final Object DUMMY = new Object()
. So the map is populated with your object as key, and a value that is of no interest.
这篇关于Java HashSet与HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!