表示我把你的代码直接贴过来,除掉了包名,一切OK啊!运行的也没问题,是不是没导包?package com.wenfengkeji.heima;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class Demo15 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap<Person, String> map = new TreeMap<Person, String>(
new ComparatorByNameDmeo());
map.put(new Person("lisi1", 29), "南京");
map.put(new Person("lisi2", 29), "上海");
map.put(new Person("lisi3", 29), "北京");
map.put(new Person("lisi4", 29), "天津");
Iterator<Map.Entry<Person, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Person, String> me = it.next();
Person key = me.getKey();
String name = key.getName();
int age = key.getAge();
String value = me.getValue();
System.out.println(name + ",,," + age + "...." + value);
}
}
}
class ComparatorByNameDmeo implements Comparator {
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if (!(o1 instanceof Person))
throw new ClassCastException("类型转换异常");
Person p1 = (Person) o1;
Person p2 = (Person) o2;
int temp = p1.getName().compareTo(p2.getName());
return (temp == 0) ? temp = p1.getAge() - p2.getAge() : temp;
}
}
class Person {
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(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return name + ":" + age;
}
/*
* public int hashCode(String name,int age){ return
* this.name.hashCode()+this.age*30; } public boolean equals(){ return
* this.name.equals(name)&&this.age==age; }
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Person))
throw new ClassCastException("类型转换错误");
{
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age;
}
}
/*
* public int compareTo(Object o) { // TODO Auto-generated method stub
* if(!(o instanceof Person)) throw new ClassCastException("类型转换异常"); Person
* p=(Person)o; int temp=this.getName().compareTo(p.getName()); return
* (temp==0)?this.getAge()-p.getAge():temp; }
*/
}
|