请前辈们讲解下如下代码中// 重写equals方法部分代码的执行思路
其中的equals(Object obj) { if (this == obj) {........中定义的obj和this指的是什么,
麻烦将stu3对象代入讲解一下...........大二java初学者--谢谢--谢谢
import java.util.*;
class Student {
private String id;
private String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
// 重写toString()方法
public String toString() {
return id + ":" + name;
}
// 重写hashCode方法
public int hashCode() {
return id.hashCode();
}
// 重写equals方法
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student stu = (Student) obj;
boolean b = this.id.equals(stu.id);
return b;
}
}
public class Example11 {
public static void main(String[] args) {
HashSet hs = new HashSet();
Student stu1 = new Student("1", "Jack");
Student stu2 = new Student("2", "Rose");
Student stu3 = new Student("2", "Rose");
hs.add(stu1);
hs.add(stu2);
hs.add(stu3);
System.out.println(hs);
}
}
this指的是引用的对象本身,obj是代入的对象。
比如:添加语句boolean b1=stu3.equals(stu3),当程序运行到此的时候,会发现两个stu3,第一个stu3里边有一个equals程序,这个程序的变量(obj)是第二个stu3,然后程序运行到equals里边,在equals里边的this指代的就是第一个stu3,由于第一个stu3是this,第二个stu3是obj,所以this==obj,则b1返回true。
this代表每次调用的 本身
obj,代表比较的对象
hs.add(stu3);
程序会做这些事:
1.计算stu3的hash值(调用student的hashCode方法)
2.跟hs中的其他对象比较
2.1若没相同的hashCode,添加成功
2.2若有相同的hashCode,调用equls方法