public class EqualsDemo {
public static void main(String[] args) {
String str0 = "Hello";
String str1 = "Hello";
System.out.println("str0==str1"+(str0==str1));
}
}
运行结果:
str0==str1true
public static void main(String[] args) {
String str0 = "Hello";
String str1 = new String("Hello");
System.out.println("str0==str1:"+(str0==str1));
}
运行结果:
str0==str1:false
比较的是首地址,所以不相等。
public class EqualsDemo {
public static void main(String[] args) {
Dog dog0 = new Dog("zhangsan");
Dog dog1 = new Dog("zhangsan");
System.out.println(("dog0.equals(dog1):")+dog0.equals(dog1));
}
}
运行结果:
dog0.equals(dog1):false
public class EqualsDemo {
public static void main(String[] args) {
Dog dog0 = new Dog("zhangsan");
Dog dog1 = new Dog("zhangsan");
System.out.println(("dog0.equals(dog1):")+dog0.getDogName().equals(dog1.getDogName()));
}
}
运行结果:
dog0.equals(dog1):true
hashCode方法
未使用hashCode前
public class Dog{
private int age;
private String dogName;
public Dog(int age, String dogName) {
this.age = age;
this.dogName = dogName;
}
}
public class EqualsDemo {
public static void main(String[] args) {
Dog dog1 = new Dog(5,"xiaobai");
Dog dog2 = new Dog(5,"xiaobai");
Dog dog3 = new Dog(5,"xiaohei");
System.out.println(dog1.hashCode());
System.out.println(dog2.hashCode());
System.out.println(dog3.hashCode());
Set<Dog> dogSet = new HashSet<>();
System.out.println(dog1);
dogSet.add(dog1);
System.out.println(dog2);
dogSet.add(dog2);
System.out.println(dog3);
dogSet.add(dog3);
System.out.println(dogSet.size());
System.out.println(dog1==dog2);
System.out.println(dog1.equals(dog2));
}
}
运行结果:
1163157884
1956725890
356573597
com.filedemo.Dog@4554617c
com.filedemo.Dog@74a14482
com.filedemo.Dog@1540e19d
3
false
false
使用hashCode后
public class Dog{
private int age;
private String dogName;
public Dog(int age, String dogName) {
this.age = age;
this.dogName = dogName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dog dog = (Dog) o;
if (age != dog.age) return false;
return dogName != null ? dogName.equals(dog.dogName) : dog.dogName == null;
}
@Override
public int hashCode() {
int result = age;
result = 31 * result + (dogName != null ? dogName.hashCode() : 0);
return result;
}
}
public class EqualsDemo {
public static void main(String[] args) {
Dog dog1 = new Dog(5,"xiaobai");
Dog dog2 = new Dog(5,"xiaobai");
Dog dog3 = new Dog(5,"xiaohei");
System.out.println(dog1.hashCode());
System.out.println(dog2.hashCode());
System.out.println(dog3.hashCode());
Set<Dog> dogSet = new HashSet<>();
System.out.println(dog1);
dogSet.add(dog1);
System.out.println(dog2);
dogSet.add(dog2);
System.out.println(dog3);
dogSet.add(dog3);
System.out.println(dogSet.size());
System.out.println(dog1==dog2);
System.out.println(dog1.equals(dog2));
}
}
运行结果:
-2069661338
-2069661338
-2069655448
com.filedemo.Dog@84a37966
com.filedemo.Dog@84a37966
com.filedemo.Dog@84a39068
2
false
true