question_018-JAVA之Map之TreeMap键为自定义对象


JAVA之Map之


TreeMap键为自定义对象


--------------------------------------------


TreeMap

唯一性和强制排序性。。


比HashMap多一个强制排序的功能


--------------------------------------------

TreeMap

键:Student 【自定义对象

值:String


---------------Student-----------------------

package com.lyMapTreeMap;


/**
 * TreeMap必须实现Comparable接口,才能比较
 * @author Jack
 *
 */
public class Student implements Comparable<Student>{
private String name;
private int age;

public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}

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;
}

继承自比较器接口,实现了比较方法

@Override // 
public int compareTo(Student o) {
int num = this.getAge() - o.getAge();
int num2 = num == 0? this.getName().compareTo(o.getName()):num;
return num2;
}
}


·····················测试·······················


package com.lyMapTreeMap;


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


/**
 * TreeMap:
 * 键:Student【自定义对象】
 * 值:String
 * 
 * @author Jack
 */
public class TreeMapDemo {
public static void main(String[] args) {
// 创建TreeMap集合
Map<Student,String> tm = new TreeMap<Student,String>();

// 创建学生对象
Student s1 = new Student("学士1", 21 );
Student s2 = new Student("学士2", 22 );
Student s3 = new Student("学士3", 23 );
Student s4 = new Student("学士4", 24 );
Student s5 = new Student("学士3", 23 );

tm.put(s1, "唐朝");
tm.put(s2, "宋朝");
tm.put(s3, "元朝");
tm.put(s4, "明朝");
tm.put(s5, "清朝");

Set<Student> set = tm.keySet();
for(Student key : set){
String value = tm.get(key);

System.out.println(key.getName() + "---"+key.getAge() +"--"+value);
}
}
}


·········结果············


学士1---21--唐朝
学士2---22--宋朝
学士3---23--清朝
学士4---24--明朝


··························




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值