1. ==为关系运算符,其作用是r检查如果两个操作数的值是否相等,如果相等则条件为真。
1.1 对于基本数据类型(byte,short,int,long,char,boolean,float,double),比较的是具体的数值。
1.2 对于引用数据类型(对象,数组),比较的是他们在内存中的地址。
int a = 5; int b = 5; System.out.println(a == b);//结果为true Student s1 = new Student(); Student s2 = new Student(); System.out.println(s1 == s2);//结果为false
2. equals是超类object具有的方法,因此所有的引用类型都具有这个方法。用来检测两个对象是否相等
.2.1 equals()方法默认比较的是对象的内存地址,和==功能一样。
Student s1 = new Student(); Student s2 = new Student(); //结果和 == 关系运算符一样,都为false System.out.println(s1.equals(s2));
2.2 如果重写该方法,一般是比较对象的属性值
//equals方法的源代码 public boolean equals(Object obj) { return (this == obj); }
3. 重写equals方法
3.1 student类
public class Student { private int age; @Override public boolean equals(Object o) { if (this == o) return true; //判断传入的对象是否为Student类的一个实例化对象 if (!(o instanceof Student)) return false; Student student = (Student) o; return (this.age == student.age); } }
3.2 EqualsTest类
public class EqualsTest { public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(); System.out.println(s1 == s2);//结果为false System.out.println(s1.equals(s2));//结果为true } }