Java的equals方法使用方法

2023-05-16

在标准Java库中包含150多个equals方法的实现,这里给出一个比较完美的实现方法。

1)显示参数命名为otherObject,稍后需要将它转换成另一个叫做other的变量。
2)检测this与otherObject是否引用同一个对象:
if(this == otherObject) return true;
这条语句只是一个优化。实际上这是一种经常使用的形式。
3)检测otherObject是否为null,如果为null,返回false。这项检测很必要。
if(otherObejct == null) return false;
比较this与otherObject是否为属于同一个类。如果equals的语义在每个子类中有所改变,就使用getClass检测:
if(getClass() != otherObject.getClass())  return false;
如果所有的子类都拥有统一的语义,就使用instanceof检测:
if(!(otherObejct instanceof ClassName))  return false;
4)将otherObject转换为相应的类类型变量:
ClassName other = (ClassName)otherObject;
5)现在开始对所有需要比较的域进行比较了。使用==比较基本类型域,使用equals比较对象域。如果所有的域都匹配,就返回true,否则返回false。
return field == other.field&&field.equals(other.field)&&...;
如果在子类中重新定义equals,就要在其中包含调用super.equals(other)。

import java.util.*;

public class EqualsTest
{
	public static void main(String[] args)
	{
		Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
		Employee alice2 = alice1;
		Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
		Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
		
		System.out.println("alice1 == alice2: " + (alice1 == alice2));
		System.out.println("alice1 == alice3: " + (alice1 == alice3));
		System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));
		System.out.println("alice1.equals(bob): " + alice1.equals(bob));
		System.out.println("bob.toString(): " + bob);
		
		Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
		Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
		boss.setBonus(5000);
		System.out.println("boss.toString(): "+ boss);
		System.out.println("carl.equals(boss): " + carl.equals(boss));
		System.out.println("alice1.hashCode(): " + alice1.hashCode());
		System.out.println("alice3.hashCode(): " + alice3.hashCode());
		System.out.println("bob.hashCode(): " + bob.hashCode());
		System.out.println("carl.hashCode(): " + carl.hashCode());
	}
}

class Employee
{
	public Employee(String n, double s, int year, int month, int day)
	{
		name = n;
		salary = s;
		GregorianCalendar calendar = new GregorianCalendar(year, month-1, day);
		hireDay = calendar.getTime();
	}
	
	public String getName()
	{
		return name;
	}
	
	public double getSalary()
	{
		return salary;
	}
	
	public Date getHireDay()
	{
		return hireDay;
	}
	
	public void raiseSalary(double byPercent)
	{
		double raise = salary*byPercent/100;
		salary += raise;
	}
	
	public boolean equals(Object otherObject)
	{
		//a quick test to see if the objects are identical
		if(this == otherObject)
			return true;
		//must return false if the explicit parameter is null
		if(otherObject == null)
			return false;
		//if the classes don't match, they can't be equal
		if(getClass() != otherObject.getClass())
			return false;
		//now we know otherObject is a non-null Employee
		Employee other = (Employee)otherObject;
		//test whether the fields have identical values
		return name.equals(other.name)
			&& salary == other.salary
			&& hireDay.equals(other.hireDay);
	}
	
	public int hashCode()
	{
		return 7*name.hashCode() + 11*new Double(salary).hashCode()
			+ 13*hireDay.hashCode();
	}
	
	public String toString()
	{
		return getClass().getName() + "[name=" + name
			+ ",salary=" + salary + ",hireDay=" + hireDay
			+ "]";
	}
	
	private String name;
	private double salary;
	private Date hireDay;
}

class Manager extends Employee
{
	public Manager(String n, double s, int year, int month, int day)
	{
		super(n, s, year, month, day);
		bonus = 0;
	}
	
	public double getSalary()
	{
		double baseSalary = super.getSalary();
		return baseSalary + bonus;
	}
	
	public void setBonus(double b)
	{
		bonus = b;
	}
	
	public boolean equals(Object otherObject)
	{
		if(!super.equals(otherObject))
			return false;
		Manager other = (Manager)otherObject;
		//super.equals checked that this and other belong to the same class
		return bonus == other.bonus;
	}
	
	public int hashCode()
	{
		return super.hashCode() + 17*new Double(bonus).hashCode();
	}
	
	public String toString()
	{
		return super.toString() + "[bonus=" + bonus + "]";
	}
	
	private double bonus;
}

运行结果:
--------------------Configuration: <Default>--------------------
alice1 == alice2: true
alice1 == alice3: false
alice1.equals(alice3): true
alice1.equals(bob): false
bob.toString(): Employee[name=Bob Brandson,salary=50000.0,hireDay=Sun Oct 01 00:00:00 CST 1989]
boss.toString(): Manager[name=Carl Cracker,salary=80000.0,hireDay=Tue Dec 15 00:00:00 CST 1987][bonus=5000.0]
carl.equals(boss): false
alice1.hashCode(): 377780067
alice3.hashCode(): 377780067
bob.hashCode(): 955285015
carl.hashCode(): 386513600

Process completed.


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java的equals方法使用方法 的相关文章

随机推荐

  • PX4板载计算机外部控制

    板载计算机外部控制主要是使用第三方机载计算机 xff08 如 xff1a Intel Aero Jetson TX2 Jetson Nano 其他类型minipc xff09 等通过mavlink协议实现对飞控参数的获取和机载端控制 xff
  • PX4无人机配置4G空地多机组网系统

    前言 使用4G网络实现无人机地面端与天空端实时通信 xff0c 并基于蒲公英cloudVPN组网技术实现广域网内的异地组网 xff0c 进一步实现不限制距离的空地多机远程组网系统 cloudVPN组网无需公网IP xff0c 需要注册一个花
  • OpenWRT配置Zerotier实现内网映射

    OpenWRT加入zerotier xff1a zerotier使用教程 OPENWRT LEDE 配置ZeroTier网络教程 子绘绘的博客 CSDN博客 Openwrt路由通过Zerotier组网实现异地内网互访 Linux加入zero
  • PX4云台控制

    一 云台硬件配置 云台采用storm32bgc无刷三轴云台 xff0c 该云台支持通过飞控控制与WBUS多通道接收机控制 这里我们采用通过pixhawk4飞控进行控制 pwm控制模式 采用三条3pin杜邦线将飞控辅助通道AUX1 3连接至云
  • 行人和人脸识别数据集

    推荐一个可应用于无人车 无人机 监控识别相关的数据集 行人和人脸检测数据集 xff08 FEEMS xff09 xff1a GitHub neverland7D Face and Pedestrian Detection Dataset F
  • Acuro二维码识别与降落对准

    什么是Aruco码 xff1f Aruco码能做什么 xff1f 搜索任务 自主降落等辅助标识 替代复杂任务中较难识别的目标 xff08 短期替代 长期替代 xff09 SLAM中的地标 反解无人机位置 实现定点 最容易识别的目标之一 1
  • ADRC控制算法在多旋翼飞行器上的应用

    基础理论知识 xff1a 程序中涉及的部分知识点参考如下链接 xff1a ADRC算法以及参数整定 xff1a 关于ADRC算法以及参数整定 xff08 调参 xff09 的一些心得体会 西涯先生的博客 CSDN博客 adrc控制算法 AD
  • 补充总结:现代控制理论

    补充内容 xff1a 现代控制理论与经典控制理论的区别 xff1a 经典控制理论主要是借助于传递函数研究系统输出与输入的关系 xff0c 而不管系统到底内部结构如何 xff0c 好比一个未知的 黑匣子 现代控制理论相对而言是要研究系统内部的
  • 网上英语学习资源大整理

    翻译 http www bilinguist com 汉英论坛 xff0c 高手云集 url http www chinatranslate net url 中国翻译网 xff0c 号称全国最大的翻译专业网站 url http gb tra
  • 使用PID和LQR控制器进行多旋翼飞行器控制

    任务内容 通过调整PID和LQR控制器以实现稳定悬停的多旋翼飞行器 xff0c 运用在无论是在仿真中还是在实际系统中 参考内容 LQR控制部分基础参考内容 xff1a LQR控制器 参考链接 xff1a Linear Quadratic R
  • Ardupilot板载计算机上云实践——第一步

    阿里云ECS在基于MAVLink的飞行器的数据中转与日志上云应用 自己先搭建了一个Demo用于测试稳定性 xff0c 访问地址 xff1a http 182 92 127 202 8123 Ardupilot 官方在今年 xff08 202
  • ADRC Ardupilot代码分析

    记录一下自己对于Ardupilot ADRC控制代码的一些理解 GitHub链接 ADRC Active Disturbance Rejection Control by MichelleRos Pull Request 20243 Ard
  • Phillweston 自动驾驶 决策规划算法 面经

    By Phillweston 注 xff1a 原创链接如下 xff1a 详细 xff01 自动驾驶规划控制算法工程师面经 xff08 具体题目 43 回答思路 xff09 本人引用了此链接中的提问内容 xff0c 并根据自己的想法写了部分回
  • OpenWRT 分流DNS的设置

    文章出处 xff1a OpenWRT 分流DNS的设置 Issue 57 luckyyyyy blog 我自己根据实际需要基于上方的链接内容进行了相关补充 OpenWRT配置IPv6的方法参考如下文章 xff1a OpenWRT IPv6
  • 智鹰科技——无人机线路巡检系统商业计划书

    智鹰科技 无人机线路巡检系统商业计划书 第一章 执行总结1 1 项目背景1 2 产品介绍1 3 市场分析1 4 竞争分析1 5 营销策略1 6 公司战略1 7 公司概况1 8 财务与投融资计划1 9 风险分析 第二章 项目背景2 1 国内外
  • linux环境安装nodejs和npm环境

    原文地址 前言 因为刚刚换上hexo的框架 xff0c 想利用私有部署把Twikoo评论部署在博客上 xff0c 所以需要使用liunx安装node js 网络上对于安装linux的资料很少 xff0c 在我查找了一些资料之后终于把环境配置
  • python 一些常用但总是记不住的函数

    python 一些常用但总是记不住的函数 import numpy as np transpose 转置函数 y 61 np mat span class hljs number 1 span span class hljs number
  • 每天一篇论文 316/365 用于欠驱动系统能量控制端到端学习的深拉格朗日网络

    Deep Lagrangian Networks for end to end learning of energy based control for under actuated systems 摘要 将深度学习应用于控制领域 xff0
  • Android 注解(Annotation)的入门与使用(一)

    Android 注解 xff08 Annotation xff09 的入门与使用 xff08 一 xff09 概述什么是注解 xff08 Annotation xff09 注解 xff08 Annotation xff09 用来做什么元注解
  • Java的equals方法使用方法

    在标准Java库中包含150多个equals方法的实现 xff0c 这里给出一个比较完美的实现方法 1 xff09 显示参数命名为otherObject xff0c 稍后需要将它转换成另一个叫做other的变量 2 xff09 检测this