首页 技术 正文
技术 2022年11月19日
0 收藏 689 点赞 3,743 浏览 1519 个字
/*
class A implements Comaprable<A>{
}
那么 A x = new A(); 类关系图
Object o = A; Object
Comparable c = A; | Comparable
A 实现了 Comparable 接口嘛 |-----|-----A
所以有 o instanceof A == true;
o instanceof Comparable == true; 例如ArrayList添加对象实例时,对象实例添加之后先向上转型为Object!内部用Object[]数组接收!
Arrays.sort()对Object排序的函数内部就是将 Object 向下转型为Comparable类型。
因为每个对象实现了Comparable接口,利用多态性,(Comparable)o1).compareTo(o2)将调用子类的compareTo()方法!((Comparable<Object>)o1).compareTo((Student)o2);
((Comparable<XXX>)o1).compareTo((YYY)o2);
如果想写泛型那么 XXX 要么是同一类型,要么XXX是YYY的父类!因为我们强转的Comparable是比较XXX类型数据的,
而YYY类型满足上面的条件才能成功向上转型为XXX类型!
*/class Person implements Comparable<Person>{
String name;
int age;
Person(){
name = "";
age = 0;
}
Person(String name, int age){
this.name = name;
this.age = age;
}
public String toString(){
return name + "...." + age;
} public boolean equals(Object o){
Person x = (Person)o;
return name.equals(x.name) && age==x.age;
} public int compareTo(Person o){ if(name.compareTo(o.name)==0)
return o.age - age;
return o.name.compareTo(name);
}
}class Student implements Comparable<Student>{
String name;
int age;
public Student(){
name = "";
age = 0;
}
public Student(String name, int age){
this.name = name;
this.age = age;
} public int compareTo(Student o){ if(name.compareTo(o.name)==0)
return o.age - age;
return o.name.compareTo(name);
}
}public class Test{
public static void main(String[] args){ Person p = new Person("fsf", 45);
Student s = new Student("faga", 20);
Student ss = new Student("fsfdfsf", 456);
Comparable xx = (Comparable)s;
System.out.println(xx);
cmp(s,ss);
}
public static int cmp(Object o1, Object o2){
//return ((Comparable<Object>)o1).compareTo((Student)o2); return ((Comparable)o1).compareTo((Student)o2);
}
}

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295