tsya
2007-05-19 03:55:42 UTC
是這樣的
我想要排序一個Array
元素如下
class Element implements Comparable<Element>{
int value;
String name;
public int compareTo(Element other){
return this.value-other.value;
}
Element(int n,String s){
this.value=n;
this.name=s;
}
public String toString(){
return "value = "+this.value;
}
}
在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應如何排序?
請給我一些觀念可以嗎?
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 202.132.132.7
我想要排序一個Array
元素如下
class Element implements Comparable<Element>{
int value;
String name;
public int compareTo(Element other){
return this.value-other.value;
}
Element(int n,String s){
this.value=n;
this.name=s;
}
public String toString(){
return "value = "+this.value;
}
}
在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應如何排序?
請給我一些觀念可以嗎?
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 202.132.132.7