==和equals的区别
时间: 2023-09-04 16:10:43 浏览: 43
在Java中,==操作符用于比较两个变量是否引用同一个对象。如果两个变量引用同一个对象,则它们的值相等。例如:
```
String s1 = "hello";
String s2 = "hello";
if (s1 == s2) {
System.out.println("s1 and s2 refer to the same object");
} else {
System.out.println("s1 and s2 do not refer to the same object");
}
```
输出结果为: `s1 and s2 refer to the same object`
而equals方法用于比较两个对象的值是否相等。通常,我们需要重写equals方法以便于比较自定义类型的对象。例如:
```
public class Person {
private String name;
private int age;
// constructor, getters and setters
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Person)) {
return false;
}
Person other = (Person) obj;
return this.name.equals(other.name) && this.age == other.age;
}
}
Person p1 = new Person("John", 30);
Person p2 = new Person("John", 30);
if (p1.equals(p2)) {
System.out.println("p1 and p2 have the same values");
} else {
System.out.println("p1 and p2 do not have the same values");
}
```
输出结果为: `p1 and p2 have the same values`
总的来说,==用于比较引用类型的变量是否引用同一个对象,而equals用于比较两个对象的值是否相等。在比较自定义类型的对象时,通常需要重写equals方法来实现自定义的比较逻辑。