- “==”比较基本数据类型时直接比较其存储的值;比较引用类型的变量时比较的是对象的地址。
int a =1;
int b = 1;
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println(a==b);//true
System.out.println(s1==s2);//true
System.out.println(s3==s4);//false
System.out.println(s3.equals(s4));//true
- “equals()方法的“java中大部分类都重写了equals()方法方法,所以直接比较的是两个对象的内容,如果是自己定义的类,没有重写的equals()方法,那么比较的是两个对象所指向的地址。
public class demo1{
public static void main(String[] args){
//没有重写equals()方法
Student s1 = new Student(23);
Student s2 = new Student(23);
System.out.println(s1.equals(s2));//false
}
//自己定义一个Student类
class Student{
private int age;
public Student(){}
public Student(int age){
this.age = age;
}
}
}
我自定义了一个学生类,没有重写的equals()方法,结果为假
/**
*重写equals()
*Object中的equals()方法为
*public boolean equals(Object obj) {
* return (this == obj);
* }
*/
public class Demo2{
public static void main(String[] args){
Student s1 = new Student(23);
Student s2 = new Student(23);
System.out.println(s1.equals(s2));//true
}
//自定义一个Student类,并重写equals()
class Student{
private int age;
public Student(){}
public Student(int age){
this.age = age;
}
public boolean equals(Object obj){
Student other = (Student)obj;
return this.age == other.age;
}