您的位置:首页 > 其它

集合框架--Map集合之TreeMap存储自定义对象

2016-05-09 17:33 423 查看
用TreeMap按姓名进行排序:

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

class Student {
String name;
int age;

public Student(String name,int age){
super();
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;
}
public int hashCode(){  //复写hashCode()
return name.hashCode()+age;
}

public boolean equals(Object obj){  //复写equals

if(this==obj) return true;

if(!(obj instanceof Student))  throw new ClassCastException("类型错误");  //输入类型错误

Student s = (Student)obj;//强制转换
return this.name.equals(s.name) && this.age==s.age;  //说明姓名和年龄相同则为同一元素
}

}

class  ComparatorByName implements Comparator{  //按姓名比较,继承Comparator接口
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;

int temp=s1.getName().compareTo(s2.getName());
return temp==0?s1.getAge()-s2.getAge():temp;
}
}
public class TreeMapDemo{
public static void main(String[] args){
TreeMap<Student,String> tm=new TreeMap<Student,String>(new ComparatorByName());

tm.put(new Student("lisi",38),"北京");
tm.put(new Student("zhaosi",34),"上海");
tm.put(new Student("xiaoqiang",31),"沈阳");
tm.put(new Student("wangcai",28),"大连");
tm.put(new Student("zhaosi",34),"铁岭");

Iterator<Map.Entry<Student,String>> it=tm.entrySet().iterator();

while(it.hasNext()){
Map.Entry<Student,String> me=it.next();
Student key=me.getKey();
String value=me.getValue();
System.out.println(key.getName()+":"+key.getAge()+"..."+value);
}
}

}
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: