什么时候使用“==”什么时候使用equals()
对于基本数据类型我们如果要判断两个变量是否相等我们直接使用双等“==”就好
对于引用数据类型如果我们要判断两个引用也就是两个对象是否相等我们必须使用equals()方法不然我们就无法得到自己想要的结果。
import java.util.Objects;
public class Test{
int no;
String school;
public Test() {
}
public Test(int no, String school) {
this.no = no;
this.school = school;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public static void main(String[] args) {
Test test =new Test(123,"北疆大学");
Test test2 =new Test(123,"北疆大学");
System.out.println(test.school.equals(test2.school));
// String str1="1234";
// String str2="1234";
Test test3= new Test(123,new String("北京大学"));
Test test4= new Test(123,new String("北京大学"));
System.out.println(test3.school.equals(test4.school));
}
@Override
public String toString() {
return "Test{" +
"no=" + no +
", school='" + school + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Test test = (Test) o;
return no == test.no && Objects.equals(school, test.school);
}
}