引言:这个equals()方法重写在我这篇博客已经提到了,这里单独拿出来便于观看。
Java --- 字符串(就这一篇带你学习字符串的绝大多数内容)-CSDN博客
equals():用这种方法比较两个用String类定义的对象,如果两个字符串具有相同的字符与长度,那么就会返回true。
用equals()方法注意:
1.不要使用该方法比较对象类型
2.不要使用该方法比较字符串常量。
3.不要使用该方法比较两个浮点型或双精度型的值,因为浮点数子啊计算机捏表示近似值,会导致结果不准确。
这里我定义一个People类和一个继承People类的Student类:
如果想比较两个类的值,就需要将equals()方法重写,也就是将该方法从Object类中继承并覆盖
public class People {
private int id;
private String name;
public People(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Student extends People{
private double score;
public Student(int id, String name) {
super(id, name);
}
public Student(int id, String name, double score) {
super(id, name);
this.score = score;
}
}
这里我就是为了举例子,在People重写一个equals()方法:
1.判断是否为同一对象
2.将不是People类对象筛除
3.强转想比较的对象,并比较其成员变量
public class People {
private int id;
private String name;
public People(int id, String name) {
this.id = id;
this.name = name;
}
public boolean equals(Object obj){
//1.同一对象判断
if(obj == this)
return true;
//2.不是People类对象
if(!(obj instanceof People))
return false;
//3.强转成People类对象,比较两个对象的id与name
People p = (People)obj;
return p.id == this.id && p.name.equals(this.name);
}
}
随后我把样例主方法放在People类内分析,来更深刻理解一下:
public class People {
private int id;
private String name;
public boolean equals(Object obj){
//同一对象判断
if(obj == this)
return true;
//不是People类对象
if(!(obj instanceof People))
return false;
//强转成People类对象
People p = (People)obj;
//比较两个对象的id与name
return p.id == this.id && p.name.equals(this.name);
}
public People(int id, String name) {
this.id = id;
this.name = name;
}
public static void main(String[] args) {
People p1 = new People(1,"zhangsan");
System.out.println(p1.equals(p1));//p1与p1比较结果:true
People p2 = new People(1,"zhangsan");
System.out.println(p1.equals(p2));//p1与p2比较结果:true
People p3 = new People(2,"lisi");
System.out.println(p1.equals(p3));//p1与p3比较结果:false
People p4 = new Student(1,"zhangsan",521);
System.out.println(p1.equals(p4));//p1与p4比较结果:true
People p5 = new Student(1,"zhangsan",125);
System.out.println(p4.equals(p5));//p4与p5比较结果:true,但是注意因为咱们重写方法时候没有比较score的值以至于结果返回true
}
}
OK本期就介绍到这里了,感谢收看,记得三连支持一下。