本帖最后由 qinhaihang 于 2015-6-12 10:55 编辑
我的代码如下:
- package com.test;
- import java.util.*;
- class Student {
- private String name;
- private int age;
-
- public Student(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @Override
- public String toString() {
- return "Student [name=" + name + ", age=" + age + "]";
- }
-
- }
- public class Test4 {
- public static void main(String[] args) {
- //Student stu = new Student("lisi", 20);
- //System.out.println(stu);
- //使用TreeMap可以传入比较器comparator
- TreeMap<String, Student> className = new TreeMap<String,Student>(new MyComparator());
-
- //建立班级容器(唯一性出问题)
- className.put("class1",new Student("lisi",20));
- className.put("class1", new Student("qinhaihang",18));
- className.put("class2", new Student("haihangqin",19));
- className.put("class2", new Student("hanghaiqin",17));
-
- //使用迭代器打印键值
- //将Map键存到Set集合中
- Set<String> keyset = className.keySet();
- Iterator<String> it = keyset.iterator();
- while(it.hasNext()){
- String key = it.next();
- Student value = className.get(key);
- System.out.println("Key:"+key+",Value:"+value);
- }
- }
- }
- class MyComparator implements Comparator<Object> {
- @Override
- public int compare(Object o1, Object o2) {
- String s1 = (String)o1;
- String s2 = (String)o2;
- int num = s1.compareTo(s2);
- if(num==0){
- num=-1;
- }
- return num;
- }
-
- }
复制代码 打印结果,key可以打印出来,但是value全是null。
求教大神啊,看看为什么会这样
|
|