equals 和 ==
equals和hashcode
为什么同时重写
why??
处于业务需要,我们需要经常需要重写equals,重写了equals如果不重写hashcode会怎样
如果两个‘相等对象’其中一个放入hashmap,以另一个来取根本取不到,因为他们hashcode不一样。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33package com.whisper;
/**
* Created by whisper on 16/7/13.
*/
class Cat{
private String color;
private int age;
public Cat(String color, int age) {
this.color = color;
this.age = age;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cat cat = (Cat) o;
if (age != cat.age) return false;
return !(color != null ? !color.equals(cat.color) : cat.color != null);
}
/* @Override
public int hashCode() {
int result = color != null ? color.hashCode() : 0;
result = 31 * result + age;
return result;
}*/
}
测试:1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.whisper;
import java.util.*;
public class Main {
public static void main(String[] args) {
Cat cat = new Cat("red",20);
Cat cat1 = new Cat("red",20);
Map cats = new HashMap<Cat,Integer>();
cats.put(cat,10);
System.out.printf(String.valueOf(cats.get(cat1)));
}
}
如果