【Map的使用】TreeMap的基本使用

/*HashMap和TreeMap二者区别
HashMap:保证键不能重复的原理和HashSet是一样的
TreeMap:根据键来排序的,排序的原理和TreeSet是一样的
*/
//TreeMap的基本使用
package com.Map;
import java.util.*;
class StudentTM implements Comparable<StudentTM>
{
private String name;
private int age;
public StudentTM(){}
public StudentTM(String name,int age)
{
this.name=name;
this.age=age;
}
//按姓名排序
public int compareTo(StudentTM stu)
{
int num=this.name.compareTo(stu.name);
return num==0?this.age-stu.age:num;
}

public int hashCode()
{
return name.hashCode()+age*36;

public boolean equals(Object obj)
{
if(!(obj instanceof StudentTM))
throw new ClassCastException("equlas类型转换异常");
StudentTM stuTM=(StudentTM)obj;
return this.name.equals(stuTM.name)&& this.age==stuTM.age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
public String toString()
{
return name+","+age;
}
}
//自己定义的排序方式,根据年龄排序
class ComByAge implements Comparator<StudentTM>
{
public int compare(StudentTM s1,StudentTM s2)
{
int num=s1.getAge()-s2.getAge();
return num==0?s1.getName().compareTo(s2.getName()):num;
}
}


public class TestTreeMap {
public static void main(String[] args) {
ComByAge byAge=new ComByAge();
TreeMap<StudentTM,String> map=new TreeMap<StudentTM,String>(byAge);//按自定义的按年龄排序
// TreeMap<StudentTM,String> map=new TreeMap<StudentTM,String>();//按常规的键排序
//TreeMap是根据键来排序的,根据键排序,和TreeSet的原理是一样的
map.put(new StudentTM("yoti",28),"茂名");
map.put(new StudentTM("MM", 23),"化州");
map.put(new StudentTM("SZ",2), "深圳");
map.put(new StudentTM("MM", 23),"beijing");
Set<Map.Entry<StudentTM, String>> en=map.entrySet();
Iterator<Map.Entry<StudentTM, String>> ite=en.iterator();
while(ite.hasNext())
{
Map.Entry<StudentTM, String> entry=ite.next();
StudentTM key=entry.getKey(); //得到键
String  value=entry.getValue();//得到值
System.out.println(key+","+value);
}
}
}
/*演示效果1:TreeMap<StudentTM,String> map=new TreeMap<StudentTM,String>();//按常规的键排序 输出效果
MM,23,beijing
SZ,2,深圳
yoti,28,茂名
*/
/*
演示效果2:TreeMap<StudentTM,String> map=new TreeMap<StudentTM,String>(byAge);//按自定义的按年龄排序
SZ,2,深圳
MM,23,beijing
yoti,28,茂名*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值