一个有关JAVA集合的问题,高手请进?

2024-12-23 09:16:22
推荐回答(2个)
回答1:

给你改了打错的地方。现在好了。
import java.util.*;

public class TestMap {
public static void main(String args[]) {
TreeMap map = new TreeMap(
new Comparator() {
public int compare(Key a, Key b) {
return a.compareTo(b);
}
});
Student stu0 = new Student("zhangsan", 18);
Student stu1 = new Student("lisi", 20);
map.put(new Key(stu0.age), stu0);
map.put(new Key(stu1.age), stu1);
Set set = map.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Key o = (Key) it.next();
System.out.println(map.get(o));
}
}
}

class Student {
String name;
int age;

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public String toString() {
return ("name:" + name + "\tage:" + age);
}
}

class Key implements Comparable {
private int age;

public Key(int age) {
this.age = age;
}

public int compareTo(Object o) {
Key other = (Key) o;
return (this.age - other.age);
}
}

回答2:

TreeMap map=new TreeMap(new Comparator(){
你的类名是TestMap