本帖最后由 程序爱好者 于 2014-4-16 19:45 编辑
import java.util.*;
public class Dome {
public static void main(String[] args) {
TreeMap<Student,String> tm=new TreeMap<Student,String>(new com());
tm.put(new Student("张三",19), "北京");
tm.put(new Student("李四",20), "上海");
// map.put(new Student("王五",25), "深圳");
tm.put(new Student("王五",25), "深圳");
tm.put(new Student("赵六",22), "北海");
Set<Map.Entry<Student,String>> s=tm.entrySet();
Iterator<Map.Entry<Student, String>> en=s.iterator();
while(en.hasNext())
{
Map.Entry<Student,String> kry=en.next();
Student key=kry.getKey();
String value=kry.getValue();
System.out.println(key+":"+value);
}
}
}
import java.util.*;
public class Student implements Comparable<Student> {
private String name;
private int age;
public int compareTo(Student s)
{
// Student s=(Student)o;
int num=new Integer(this.age).compareTo(new Integer(s.age));
if (num==0) {
return this.name.compareTo(s.name);
}
return num;
}
public Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int hashCode()
{
return name.hashCode()+age*37;
}
public boolean equals(Object obj)
{
if (! (obj instanceof Student)) {
throw new ClassCastException("类型不匹配");
}
Student s=(Student)obj;
return this.name.equals(s.name)&&this.age==s.age;
}
}
import java.util.*;
public class com implements Comparator<Student>{
public int compare(Student s1,Student s2)
{
int num=s1.getName().compareTo(s2.getName());
if (num==0) {
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return num;
}
}
结果是:
map.lianxi.Student@bd5a8:北京
map.lianxi.Student@cdc31:上海
map.lianxi.Student@e5006:深圳
map.lianxi.Student@1175c6:北海
为什么会这样 不是想象中的那样 前面是姓名年龄后面是地址。怎么好像出现乱码
|
|