????先看下面的代码,想下会输出什么?
public class HashSetDemo {
public static void main(String[] args) {
Person p1 = new Person("a", 1);
Person p2 = new Person("a", 1);
HashSet<Person> hashSet = new HashSet<>();
hashSet.add(p1);
hashSet.add(p2);
System.out.println(hashSet.size());
System.out.println(p1.equals(p2));
}
}
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public boolean equals(Person p) {
return this.name.equals(p.name) && this.age == p.age;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
2
true
有哪位大佬知道是为什么?
????如果去掉Person的equals(Person p)方法,改成重写Object的equals(Object o)结果是什么?
import java.util.HashSet;
import java.util.Objects;
public class HashSetDemo {
public static void main(String[] args) {
Person p1 = new Person("a", 1);
Person p2 = new Person("a", 1);
HashSet<Person> hashSet = new HashSet<>();
hashSet.add(p1);
hashSet.add(p2);
System.out.println(hashSet.size());
System.out.println(p1.equals(p2));
}
}
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
System.out.println("equals(Object o)");
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
输出:
1
true
以上的输出为什么?明明HashSet方法add时是指定了范型类型Person的,不应该是调用equals(Person p)方法吗?
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
// 这里的E应该是Person类型的,但是考虑范型擦除,最终调用哪个方法还需要看看擦除后是何类型?
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 这里进行key是否相同的对比,比较引用和equals方法对比内容,但是这里key.equals(k)到底调用的是
// key自定义类型的equals实现,还是覆写Object的equals方法
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}