现在有一个自定义学生的学生类,里面有name属性,和age属性,我们如何去比较大小?
class Student{
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Test {
public static void main(String[] args){
Student student1 = new Student("zhangsan",18);
Student student2 = new Student("lisi",20);
}
}
自定义类型因为有很多的属性,编译器不知道怎么去比较大小,因此需要我们自定义比较规则.让他去具备可比较的功能
方法1:实现Comparable接口,重写comparaeTo方法(自定义)
class Student implements Comparable<Student>{
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name+ '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
}
public class Test {
public static void main(String[] args){
Student student1 = new Student("zhangsan",18);
Student student2 = new Student("lisi",20);
if(student1.compareTo(student2)>0){
System.out.println("student1 > student2");
}else if(student1.compareTo(student2) == 0){
System.out.println("student==student");
}else{
System.out.println("student1 < student2");
}
}
}
如果需求更换,需要临时换一个比较规则,此时使用comparable就不好修改了
方法2:Comparator接口
我们可以写一个类,实现Comparator接口,重写compare接口,可以这个类(比较器)作为参数传递,相当于给一个类传递了比较规则
import java.util.Comparator;
class Student implements Comparable<Student>{
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name'" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
}
class NameComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
}
public class Test {
public static void main(String[] args){
Student student1 = new Student("zhangsan",18);
Student student2 = new Student("lisi",20);
NameComparator nameComparator = new NameComparator();
if(nameComparator.compare(student1,student2)>0){
System.out.println("student1 > student2");
}else if (nameComparator.compare(student1,student2)<0){
System.out.println("student < student2");
}else {
System.out.println("student1 == student2");
}
}
}
comparable和comparator接口返回值是 Int类型 可以比较大小,而equals方法返回类型是 boolean,
只能判断是否相等