qq_37859539
维1
2017-09-08 13:58

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

1
  • 集合框架
  • java

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条回答

为你推荐