Java 将equals override为比较所有object的方法

本文介绍了一个自定义 Java 类 Student 的实现,该类重写了 equals 和 hashCode 方法,并实现了 Comparable 接口来支持对象间的比较。文章展示了如何正确地比较不同 Student 对象的实例,并通过示例代码说明了 equals 方法的正确使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java 默认的equals只能比较同类型的object,一旦比较对象类型不同就会报错。下面是当类型不同时返回false避免报错的方法。

Example:

public class Student implements Comparable<Student> {
	private String name;
	private int id;

	public Student(String name, int id) {
		this.name = name;
		this.id = id;
	}

	public String toString() {
		return "Name: " + name + ", Id: " + id;
	}

	public int compareTo(Student other) {
		if (id < other.id) {
			return -1;
		} else if (id == other.id) {
			return 0;
		} else {
			return 1;
		}
	}

	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		} else if (!(obj instanceof Student)) {
			return false;
		} else {
			return compareTo((Student) obj) == 0;
		}
	}

	/* If we override equals we must have correct hashCode */
	public int hashCode() {
		return id;
	}
}
Driver:
import java.util.ArrayList;
import java.util.Collections;

public class Driver {
	public static void main(String[] args) {
		ArrayList<Student> roster = new ArrayList<Student>();

		roster.add(new Student("Mary", 10));
		roster.add(new Student("Bob", 1));
		roster.add(new Student("Laura", 17));
		roster.add(new Student("Albert", 34));

		/* Collection is sorted by id */
		Collections.sort(roster);
		for (Student s : roster) {
			System.out.println(s);
		}
		
		/* equals method tests */
		Student s1 = new Student("John", 10);
		Student s2 = new Student("John", 10);
		Student s3 = new Student("Mary", 20);

		System.out.println(s1.equals(s2));
		System.out.println(s2.equals(s1));
		System.out.println(s1.equals(s3));
		System.out.println(s1.equals(null));
	}
}
输出为:
Name: Bob, Id: 1
Name: Mary, Id: 10
Name: Laura, Id: 17
Name: Albert, Id: 34
true
true
false
false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值