以int类型为案列
比较的思路:将比较的数据作差,然后返回一个int类型的数据,将这个int类型的数值,按照 =0 <0 >0
int a = 10;
int b = 20;
System.out.println(a-b);//=0 <0 >0
比较String类型的
String类型实现了Compatable接口,这个接口中有一个抽象方法compareTo,String类中重写了这个方法即可
String a = "A";
String b = "B";
System.out.println(a.compareTo(b));
比较double类型数据
double a = 9.3;
double b = 0.6;
System.out.println(((Double) a).compareTo((Double) b));
比较自定义的数据类型
内部比较器
package wanggng;
public class Stuedent01 implements Comparable<Stuedent01>{
private int age;
private double height;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Stuedent01{" +
"age=" + age +
", height=" + height +
", name='" + name + '\'' +
'}';
}
public Stuedent01(int age, double height, String name) {
this.age = age;
this.height = height;
this.name = name;
}
@Override
public int compareTo(Stuedent01 o) {
//按照年龄进行比较
//return this.getAge() - o.getAge();
//按照身高进行比较
//return ((Double)(this.getHeight())).compareTo((Double)(o.getHeight()));
//按照姓名进行比较
return this.getName().compareTo(o.getName());
}
}
package wanggng;
public class Dome02 {
public static void main(String[] args) {
//比较两个学生
Stuedent01 s1 = new Stuedent01(12,165.5,"刚子");
Stuedent01 s2 = new Stuedent01(12,170.5,"子义");
System.out.println(s1.compareTo(s2));
}
}
外部比较器
class BiJiao03 implements Comparator<Stuedent01>{
@Override
public int compare(Stuedent01 o1, Stuedent01 o2) {
//年龄相同的情况下,比较身高,年龄不同的情况下,比较年龄
if (o1.getAge() - o2 .getAge() ==0){
return ((Double)(o1.getHeight())).compareTo((Double)(o2.getHeight()));
}else {
return o1.getAge() - o2.getAge();
}
}
}
class BiJiao01 implements Comparator<Stuedent01>{
@Override
public int compare(Stuedent01 o1, Stuedent01 o2) {
//比较年龄
return o1.getAge() - o2.getAge();
}
}
class BiJiao02 implements Comparator<Stuedent01>{
@Override
public int compare(Stuedent01 o1, Stuedent01 o2) {
//比较姓名
return o1.getName().compareTo(o2.getName());
}
}
外部比较器,和内部比较器谁好啊,答案是外部比较器,因为应用了多态,扩展性好