一,基本数据类型的比较
我们在比较基本类型的数据时,通常用“==”来判断,也比较简单
inta=3; intb=5; System.out.println(a==b);//falseSystem.out.println(a>b);//falseSystem.out.println(a<b);//true
但是当我们要比较引用的数据类型的数据时,是无法比较的,这里就要说到引用数据类的比较了
二,引用数据类型比较
1,equals()方法
classStudent { publicStringname; publicintage; publicStudent(Stringname, intage) { this.name=name; this.age=age; } } publicclassTest { publicstaticvoidmain(String[] args) { Studentstudent1=newStudent("张三", 19); Studentstudent2=newStudent("张三", 19); System.out.println(student1.equals(student2));//输出false }
这里的输出结果任然是个false,是因为在Student类中我们没有equals方法,他默认调用的是object当中的equals方法,这里要自己实现一个equals来进行比较,在Generate中找到equals()和hashCode()点击,生成一下代码段:
publicbooleanequals(Objecto) { if (this==o) returntrue; if (o==null||getClass() !=o.getClass()) returnfalse; Studentstudent= (Student) o; returnage==student.age&&Objects.equals(name, student.name); } publicinthashCode() { returnObjects.hash(name, age); }
这样就可以输出一个true了;但是equals只能比较俩个对象是否相同,并不能比较俩个对象的大小,如果要比较对象的大小,有俩种方法可以去搞:
1)实现Comparable接口
//实现接口去比较对象的大小classStudentimplementsComparable<Student>{ publicStringname; publicintage; publicStudent(Stringname, intage) { this.name=name; this.age=age; } publicbooleanequals(Objecto) { if (this==o) returntrue; if (o==null||getClass() !=o.getClass()) returnfalse; Studentstudent= (Student) o; returnage==student.age&&Objects.equals(name, student.name); } publicinthashCode() { returnObjects.hash(name, age); } //重写compareTo的方法,用于比较对象的年龄publicintcompareTo(Studento) { returnthis.age-o.age; } } publicclassTest { publicstaticvoidmain(String[] args) { Studentstudent1=newStudent("张三", 19); Studentstudent2=newStudent("张三", 20); System.out.println(student1.equals(student2)); System.out.println(student1.compareTo(student2));//输出-1 }
2)传比较器
classStudentimplementsComparable<Student> { publicStringname; publicintage; publicStudent(Stringname, intage) { this.name=name; this.age=age; } publicbooleanequals(Objecto) { if (this==o) returntrue; if (o==null||getClass() !=o.getClass()) returnfalse; Studentstudent= (Student) o; returnage==student.age&&Objects.equals(name, student.name); } publicinthashCode() { returnObjects.hash(name, age); } publicintcompareTo(Studento) { returnthis.age-o.age; } } //名字比较器classNameComparatorimplementsComparator<Student> { publicintcompare(Studento1, Studento2) { returno1.name.compareTo(o2.name); } } //年龄比较器classAgeComparatorimplementsComparator<Student> { publicintcompare(Studento1, Studento2) { returno1.age-o2.age; } } publicclassTest { publicstaticvoidmain(String[] args) { Studentstudent1=newStudent("李四", 19); Studentstudent2=newStudent("张三", 20); //System.out.println(student1.equals(student2));//System.out.println(student1.compareTo(student2));NameComparatornameComparator=newNameComparator(); //比较要比较的参数,如果student1大于student2,返回一个正数,如果相等返回0,再者就返回一个负数System.out.println(nameComparator.compare(student1, student2)); AgeComparatorageComparator=newAgeComparator(); System.out.println(ageComparator.compare(student1, student2)); } }
