作者superlubu (劲过吕布)
看板java
标题Re: [问题] 使用Comparable排序
时间Sat May 19 12:08:44 2007
※ 引述《tsya (tsya)》之铭言:
: public int compareTo(Element other){
: return this.value-other.value;
: }
就把这个改成 compare 两个 object 的 name 就行啊...
参考 API 的 String.compareTo()....
: 在main method里面做排序
: import java.util.*;
: class Sort{
: public static void main(String[] args){
: Element[] e=new Element[5];
: e[0]=new Element(1,"Apple");
: e[1]=new Element(2,"Azure");
: e[2]=new Element(5,"Apply");
: e[3]=new Element(3,"Adapt");
: e[4]=new Element(4,"Adept");
: System.out.println(Arrays.toString(e));
: Arrays.sort(e);
: System.out.println(Arrays.toString(e));
: }
: }
: 排序value 的部分非常成功
: [value = 1, value = 2, value = 5, value = 3, value = 4]
: [value = 1, value = 2, value = 3, value = 4, value = 5]
: 但是排序name就不知道怎麽写了
: 我参考这个网页
: http://www.rgagnon.com/javadetails/java-0343.html
: 但是他只有教排序String Array
: 请问含有String的Object Array应如何排序?
: 请给我一些观念可以吗?
: 谢谢
其实如果是这种 object 要排序,而且不是每次都是根据同样的 member 排序的话
会比较建议做几个 Comparator, 那麽在不同的时候无论是 sort by index 或是
sort by name, sort by size 都可以做到,只要换一个 Comparator 就可以了。
请参考 Arrays.sort(Object[] a, Comparator c) 函数
--
很多人以为 所以我要 其实我是个快
我是
大学生 告诉大家 三十岁的
怪叔叔
● ●/ ︿ ︿
/
劲\ <
劲 ●
ㄨ /\ ㄨ
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 147.8.130.225
※ 编辑: superlubu 来自: 147.8.130.225 (05/19 12:09)
※ 编辑: superlubu 来自: 147.8.130.225 (05/19 12:09)