您好,登錄后才能下訂單哦!
*類的比較需要實現接口Comparable和重寫接口的抽象方法compareTo():
*class em implements Comparable<em> //需要增加類對象的泛型
public int compareTo(em o) //負數小于,0等于,正數大于
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;
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。