equals方法和 == 的使用

equals方法的使用

equals方法

源码展示:

public boolean equals(Object obj) {
        return (this == obj);
    }

解析: equals方法默认比较使用的是== 符号进行比较的,也就是说,比较的是

直接使用 == 符号比较的就是值是否相等.地址值也要相等.

当比较的类型是基本类型的时候,比较的就是是否相等

当比较的类型是引用类型的时候,比较的就是对象的地址值

如果想要比较对象的属性值是否相等?那么就需要重写equals方法.

重写equals方法

public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

通过重写equals方法就可以实现对对象的属性的比较啦,只要属性值一样,则比较结果为true.

案例展示:

public class Test {
	public static void main(String[] args) {
		
		A a = new A("hhh", 18);
		A a1 = new A("hhh", 18);
        //重写equals方法之前
		//System.out.println(a.equals(a1));//false
       	 System.out.println(a==a1);//false
        //重写equals方法以后
        System.out.println(a.equals(a1));//true
        //使用== 比较,仍然是false 比较的是地址值.
        System.out.println(a==a1);//false
	}

}
class A{
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public A(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
}
//重写equals方法
@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		A other = (A) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
原文地址:https://www.cnblogs.com/liqbk/p/12898898.html