目录
实现比较两个对象是否相同
1.前置代码
1.学生类
2.示例
3.输出
4.原因
2.那么我们要怎么做呢?
1.对Student类中重新实现quals方法(即对equals方法重写)
2.完整代码如下:
3.具体操作
4.演示
1.示例
2.输出
3.原因
实现比较两个对象的大小
第一种: 用接口的方式实现,实现一个Comparable接口,并指定比较的类型
1.演示代码
2.示例
3.代码输出结果
第二种: 使用比较器(博主推荐使用!!!)
1.演示代码
(1)名字比较器
(2)年龄比较器
2.示例
3.代码输出结果
完结撒花✿✿ヽ(°▽°)ノ✿
class Student{
String name;
int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
}
Student student1 = new Student("fly",19);
Student student2 = new Student("fly",19);
System.out.println(student2==student1);
输出: false ==//默认比较的是两个引用的地址
原因:所有类默认继承于object,所以student1调用的是object的equals
equals的源码public boolean equals(Object obj) { return (this == obj); }
obj:obj是参数
this:随调equals谁是this
return (this == obj);
等价于return students1 == students2
//对equals方法进行重写(即自定义的equals方法)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
//实现了比较时当年龄和名字相同的情况下,认为是同一个对象
class Student{
String name;
int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
}
在IDEA右键generate(快捷键:Alt+Insert),
再选择equals() and hashCode(),一路next就ok了
System.out.println(student1.equals(student2));
输出:true
当代码运行的时候,就会使用自定义的equals方法
实现了比较时当两个对象年龄和名字相同的情况下,会被认为是同一个对象
class Student implements Comparable{
String name;
int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
}
Student student1 = new Student("初一",19)
Student student2 = new Student("初三",21);
System.out.println(student1.equals(student2));//输出: -2
System.out.println(student1.compareTo(student2));//输出: 2
Student student3 = new Student("初五",19);
System.out.println(student1.compareTo(student3));//输出: 0
class NameComparator implements Comparator {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
}
class AgeComparator implements Comparator {
@Override
public int compare(Student o1, Student o2) {
return o1.age-(o2.age);
}
}
Student student1 = new Student("初一",19);
Student student2 = new Student("初三",21);
Student student3 = new Student("初一",21);
NameComparator nameComparator = new NameComparator();
int retName = nameComparator.compare(student1, student3);
System.out.println(retName);//输出: 0
AgeComparator ageComparator = new AgeComparator();
int retAge=ageComparator.compare(student2,student3);
System.out.println(retAge);//输出: 0
System.out.println(ageComparator.compare(student1, student3));//输出: -2
System.out.println(ageComparator.compare(student3, student1));//输出: 2