Map<em,String> treemap2=new TreeMap<>(); //按照类中的方法递增
treemap2.put(new em(2,"af",30),"yes1");
treemap2.put(new em(1,"af",30),"yes2");
treemap2.put(new em(6,"af",30),"yes3");
treemap2.put(new em(5,"af",30),"yes4");
for(em f:treemap2.keySet())
{
System.out.println(f+"+"+treemap2.get(f) );
}
class em implements Comparable<em>{ //比较类时需要实现Comparable接口,泛型是对象
int id;
String name;
double salary;
public em(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(em o) { //负数小于,0等于,正数大于
if(this.salary>o.salary)
{
return 1;
}
else if(this.salary<o.salary)
{
return -1;
}
else
{
if(this.id>o.id)
{
return 1;
}
else if(this.id<o.id)
{
return -1;
}
else
{
return 0;
}
}
}
原文:https://blog.51cto.com/14437184/2421933