一.成型代码
代码如下(示例):
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"));
Student s2
= new Student(1,new String("w"));
System
.out
.println(s1
.equals(s2
));
}
}
原因:
String a = “w”; 和 String b = new String(“w”); a引用和b引用指向的地址不同,但是地址里的变量值都是“w” 所以 a == b 为false 但是用套娃(嘿嘿) 即可解决问题 使用a.equals(b) 不是使用 a ==b
转载请注明原文地址: https://lol.8miu.com/read-11111.html