Java中如何判断两个对象是否相等呢?

java问题王 Java每日一问 发布时间:2021-09-22 15:31:30 阅读数:17067 1
下文笔者将讲述Java中判断对象是否相等的方法分享,如下所示:
我们都知道在Java中对基本数据类型相等判断的方法,我们可以使用“==”符号对其进行判断, 当相等时,则返回true,否则返回false
在引用对象中,我们判断两个对象是否相等,则不能使用==符号进行判断
因为 == 符号是判断两个引用对象所指向的内存地址是否相同,相同则返回true,否则返回false
我们深知通常每一个引用对象都会在内存中开辟一块新的内存,所以我们使用“==”,肯定返回false,此时我们可以使用重写equals方法对对象进行判断
-------------------------------------------------
下面笔者将讲述重写equals方法,具体的步骤如下所示:
 
  1.使用“==”判断是否相等 
  2.验证equals()方法的参数是否为null
    当为null,则返回false
  3.当参数不为null,则如果两个对象的运行时类(通过getClass()获取)不相等,返回false,否则继续判断。
  4.自定义判断类成员是否相等
例:
自定义equals方法
当一个对象的width相同时,我们认为他们相同
package com.java265.other;
public class test {
	/*
	 * java265.com 对象是否相等的判断方法的示例分享
	 */

	public static void main(String[] args) {

		A a1 = new A(11, 12);
		A a2 = new A(11, 18);
		A a3 = new A(12, 18);

		System.out.println(a1.equals(a2)); // true
		System.out.println(a1.equals(a3)); // false
		System.out.println(a3.equals(a2)); // false
	}
}

class A {
	private int width;
	private int height;

	@Override
	public boolean equals(Object obj) {
		if (obj == null)
			return false;
		if (obj == this)
			return true;
		if (obj instanceof A) {
			A tmp = (A) obj;
			if (tmp.width == this.width)
				return true;

		}
		return false;
	}

	public A(int width, int height) {
		super();
		this.width = width;
		this.height = height;
	}

	public int getWidth() {
		return this.width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return this.height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaProblem/202109/1172.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者