equals方法怎么在Java项目中进行重写?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
比较两个对象是否是同一个对象,equals() 方法比较两个对象,是判断两个对象引用指向的是同一个对象,即比较 2 个对象的内存地址是否相等。是则返回true
Object类是所有类的父类,它的equals方法自然会被所有类继承,有一个子 类String对equals方法进行了覆盖(重写),使其具有了新功能
Java.lang.String重写了equals()方法,把equals()方法的判断变为了判断其值
当有特殊需求,如认为属性相同即为同一对象时,需要重写equals()
1.基本数据类型数据值只能用
2.对于引用数据类型,和Object的equals方法是一样的。(查看源码)
由于String类对父类Object的equals方法的重写,导致equals与= =唯一的区别在于比较对象
重写比较规则,判断两名学员(Student)是否为同一对象
Student相关属性
Id(学号)、name(姓名)、age(年龄)
如果两名学员的学号以及姓名相同,则为同一对象
1 对 Student类进行封装 然后在里面重写equals方法
方法代码:
public class Student {
private int id;
private String name;
private int age;
@Override //重写equals方法
public boolean equals(Object obj) {
if(obj instanceof Student){
Student s1=(Student)obj;
return this.id==s1.id&&this.name==s1.name&&this.age==s1.age;
}else {
System.out.println("错误");
return false;
}
}
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试类进行测试
public static void main(String[] args) {
Student s1 = new Student(1,"张三",18);
Student s2 = new Student(1,"张三",18);
Student s3 = new Student(1,"张三",18);
Student s4 = new Student(1,"张三",20);
System.out.println(s1.equals(s2));
System.out.println(s3.equals(s4));
}
以上程序执行结果
看完上述内容,你们掌握equals方法怎么在Java项目中进行重写的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。