关于equals()方法完善问题

it2023-11-09  85

一.成型代码

代码如下(示例):

public boolean equals(Object o){ if(this == o ){ return true; } if(o == null || getClass() != o.getClass() ){ return false; } Student s = (Student)o; //关键。。。。。。。。。。。。。。。。。。。。。。。。。。 return s.no == this.no && this.school.equals(s.school); }

整体代码

class Student { //学号 int no ; //所在学校 String school; //构造参数 public Student(){} public Student(int no , String school){ this.no = no ; this.school = school ; } public boolean equals(Object o){ if(this == o ){ return true; } if(o == null || getClass() != o.getClass() ){ return false; } Student s = (Student)o; //关键。。。。。。。。。。。。。。。。。。。。。。。。。。 return s.no == this.no && this.school.equals(s.school); } } public class Test03 { public static void main(String[] args){ Student s1 = new Student(1,new String("w")); //s1.school存放地址 指向堆内存地址 ,该地址存放一个"w" Student s2 = new Student(1,new String("w"));//s2.school存放地址 指向堆内存地址 ,该地址存放一个"w" System.out.println(s1.equals(s2)); //当前结果输出为:true } }

原因:

String a = “w”; 和 String b = new String(“w”); a引用和b引用指向的地址不同,但是地址里的变量值都是“w” 所以 a == b 为false 但是用套娃(嘿嘿) 即可解决问题 使用a.equals(b) 不是使用 a ==b

最新回复(0)