- package Test3;
- import java.util.Iterator;
- import java.util.Set;
- import java.util.TreeMap;
- public class Deno1111 {
- public static void main(String[] agrs) {
- TreeMap<Student,String> room2=new TreeMap<Student, String>();
- /* room2.put(new Student("赵六",26),"广东");
- room2.put(new Student("李四",20),"广西");
- room2.put(new Student("王五",24),"广州");
- room2.put(new Student("黄五",23),"上海");
- room2.put(new Student("曾七",21),"北京");
- room2.put(new Student("曾七",20),"北京"); */
- room2.put(new Student("1",26),"广东");
- room2.put(new Student("2",20),"广西");
- room2.put(new Student("3",24),"广州");
- room2.put(new Student("4",23),"上海");
- room2.put(new Student("5",21),"北京");
- room2.put(new Student("5",20),"北京");
-
- get(room2);
- }
- public static void get(TreeMap<Student,String> t){//获取集合元素,打印方法
- Set<Student> s=t.keySet();
- Iterator<Student> it=s.iterator();
- while(it.hasNext()){
- Student key=(Student)it.next();
- String value=(String)t.get(key);
- System.out.println(key.name+":"+key.age+"="+value);
- }
- }
-
- }
- class Student implements Comparable<Student>
- {//学生类
- String name;
- int age;
- Student(String name,int age){
- this.name=name;
- this.age=age;
- }
- @Override
- public int compareTo(Student obj) {
- // TODO Auto-generated method stub
- if (!(obj instanceof Student)) {
- throw new RuntimeException("类型错误");
- }
- Student std=(Student)obj;
- int nub=this.name.compareTo(std.name);
- return nub==0?new Integer(this.age).compareTo(std.age):nub;
-
- }
- }
复制代码
你这样试试就知道哪错了 ? 你的比较方法怎么看着都别扭 |