2 qq 37859539 qq_37859539 于 2017.09.08 21:58 提问

entrySet在key是自定义对象时出现错误

package GenericDemo;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo {

public static void main(String[] args) {
    TreeMap<Person, String> map = new TreeMap<Person, String>();
    map.put(new Person("chenwei", 14), "anhui");
    map.put(new Person("chenwei1", 13), "anhui");
    map.put(new Person("chenwei2", 15), "hehe");
    map.put(new Person("chenwei3", 14), "anhui");
    map.put(new Person("chenwei3", 14), "jiangsu");

    Set<Map.Entry<Person, String>> entrySet = map.entrySet();
    Iterator<Map.Entry<Person, String>> it = entrySet.iterator();
    while (it.hasNext()) {
        Map.Entry<Person, String> m = it.next();
        String value = map.get(m);
        Person p = m.getKey();
        System.out.println("name" + p.getName() + ":" + p.getAge() + "籍贯" + value);
    }
}

}
//以下是自定义对象的代码,在自定义对象中我写了compareTo方法。是不是我写的有问题??
package GenericDemo;

public class Person implements Comparable {
private String name;
private int 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;
}

public Person() {
    super();
}

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

@Override
public int compareTo(Person p) {
    // 以年龄为主要元素比较
    int temp = this.age - p.age;
    return temp == 0 ? this.name.compareTo(p.name) : temp;
}


@Override
public int hashCode() {
    //System.out.println("hashCode:" + name.hashCode() + age);
    return name.hashCode() + age;
    // return 0;
}

@Override
public boolean equals(Object obj) {
    Person p = (Person) obj;
    return this.name.equals(p.getName());
}

}

2个回答

ziwozizhan
ziwozizhan   2017.09.09 22:37
已采纳
while (it.hasNext()) {
    Map.Entry<Person, String> m = it.next();
    String value = map.get(m);
    Person p = m.getKey();
    System.out.println("name" + p.getName() + ":" + p.getAge() + "籍贯" + value);
}
    改写成
    while (it.hasNext()) {
        Map.Entry<Person, String> m = it.next();
        Person p = m.getKey();
        String value = map.get(p);
        System.out.println("name" + p.getName() + ":" + p.getAge() + "籍贯"
                + value);
    }

    继承可比较接口的类写成 implements Comparable<Person>
qq_37859539
qq_37859539 还没学到泛型
2 个月之前 回复
qq_37859539
qq_37859539 多谢,多谢,终于知道哪错了。。。
2 个月之前 回复
qq_33727653
qq_33727653   2017.09.09 12:55

仅仅大体看了一下:::: 楼主的compareTo里咋用了p.name? name不是私有化属性吗? 如果能这样用,那么 get set 不就没意义了? 无论在哪里不就都能这样用可吗?

qq_37859539
qq_37859539 name是私有属性,但我在Person自己的方法中用我的私有化属性不可以吗?
2 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片