import java.util.*;
public class MyInt Place here Place here {
public static void main(String[] args){
ArrayList
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i){this.i = i;}
public String toString(){return Integer.toString(i);}
Place here int Place here {
MyInt i2 = (MyInt)o;
return Place here ;
}
}
Code:
implements, extends, sortable, Object, Comparable
protected, public,
i – i2.i,
i,
i2.i – i,
compare(MyInt o, MyInt i2), compare(Object o, Object i2)
sort(Object o), sort(MyInt o),
compareTo(MyInt o), compareTo(Object o)
答案:
import java.util.*;
public class MyInt implements Comparable {
public static void main(String[] args){
ArrayList
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i){this.i = i;}
public String toString(){return Integer.toString(i);}
public int compareTo(Object o) {
MyInt i2 = (MyInt)o;
return i - i2.i ;
}
}
參考:12-4-3 SortedSet集合
-----------------------------------
要做排序就必須implements Comparable, 然後實作 Comparable 裡面的 compareTo.
第二各放入的物件會自動放進compareTo做比較.
並print 會自動呼叫toString()
沒有留言:
張貼留言