qq_35690469 2016-08-01 07:20 采纳率: 0%
浏览 2130

java中HashSet集合重写equals( )方法

请前辈们讲解下如下代码中// 重写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);
}
}

  • 写回答

2条回答 默认 最新

  • 散步咏凉天 2016-08-01 07:42
    关注

    this指的是引用的对象本身,obj是代入的对象。
    比如:添加语句boolean b1=stu3.equals(stu3),当程序运行到此的时候,会发现两个stu3,第一个stu3里边有一个equals程序,这个程序的变量(obj)是第二个stu3,然后程序运行到equals里边,在equals里边的this指代的就是第一个stu3,由于第一个stu3是this,第二个stu3是obj,所以this==obj,则b1返回true。

    评论

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案