集合框架--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); } } }运行结果:
相关文章推荐
- ♥ZOJ 3876-May Day Holiday【模板:蔡勒公式】
- Android ——对AsyncTask的理解和注意事项
- C#调用dll提示"试图加载格式不正确的程序"原因及解决方法
- 不要学习代码,要学会思考
- mysql常用知识
- Phalcon2.0.x 和 Laravel5 PHP框架性能测试
- 菌种的发酵方法
- Java读取属性配置文件时直接处理中文
- 键盘view 上移
- linux应用层定时器 sleep usleep
- 辞职的正确打开方式:教你如何摆脱被奴役的现状!
- 【腾讯Bugly干货】老司机教你“飙”EventBus3
- 直接插入排序思考与代码实现
- Quartz 触发器(SimpleTrigger&CronTrigger )配置说明 & cronExpression表达式
- 了解一下JAVA中的NIO模块
- 练习:租房子
- 使用Docker容器模拟分布式flume
- leetcode(4),Move Zeroes详解(python)
- SSH框架整合
- python遍历字典所有的字段