JAvaでのComparable実装オブジェクトの比較
2663 ワード
/*
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);
}
}