看板java
标 题Re: [问题]一个有关於Array的问题
发信站KKCITY (Wed Jul 19 12:04:10 2006)
转信站ptt!ctu-reader!Spring!news.nctu!news.ntust!news.ntu!bbs.ee.ntu!news.kk
※ 引述《[email protected] (._.)》之铭言:
> 如果你的 age 不会重复的话...
[-----------------------] 这不合理:)
> http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html
> 加上排序的话...
> http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html
import java.util.Arrays;
import java.util.Comparator;
class Person {
Person(String n, int a) {
this.name = n;
this.age = a;
}
String name;
int age;
}
public class Test {
public static void main(String[] args) {
Person[] ps = new Person[] { new Person("Allen", 3),
new Person("Emerson", 14), new Person("Eddy", 7) };
Arrays.sort(ps, new Comparator() {
public int compare(Object o1, Object o2) {
Person p1 = null, p2 = null;
if (o1 instanceof Person && o2 instanceof Person) {
p1 = (Person) o1;
p2 = (Person) o2;
}
if (p1.age == p2.age)
return 0;
if (p1.age > p2.age)
return 1;
else
return -1;
}
});
for (int i = 0; i < ps.length; i++)
System.out.println(ps[i].name + ps[i].age);
}
}
--
┌─────◆KKCITY◆─────┐ ◢╱ 只要你
通过身份认证 ~ ◥█
│ bbs.kkcity.com.tw │ █▉─ 免经验、五人连署即开班系板 ◥
└──《From:163.26.34.214
》──┘ ◥╲ 赶快为班上设个
秘密基地吧!
◢
--