In Java, when should you use == and equals?
In Java, “==” and equals() have different applications.
- This is used to compare the references of two objects to check if they are equal. When using “==” to compare two objects, it will return true if they reference the same memory address, and false if they do not. This is typically used to determine if two objects are the same instance.
For example:
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
System.out.println(str1 == str2); // true,因为str1和str2引用了同一个字符串常量
System.out.println(str1 == str3); // false,因为str1和str3引用的是不同的对象
- The equals() method is used to compare if the contents of two objects are equal. Typically, we need to override the equals() method to compare the contents of custom objects. By default, the equals() method behaves the same as “==” by comparing if the references of two objects are equal.
For example:
public class Person {
private String name;
private int age;
// 省略构造方法和其他代码
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
Person person3 = new Person("Alice", 25);
System.out.println(person1.equals(person2)); // false,因为name和age不同
System.out.println(person1.equals(person3)); // true,因为name和age相同
In conclusion, use “==” to determine if two objects are the same instance and use equals() to compare if their contents are equal. In most cases, we need to override the equals() method based on our specific requirements.