On the Java TreeMap

 

 

package myTest;

import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

public class MoneyHouse implements Comparable<MoneyHouse>{

private int seq;
private int money;

public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
@Override
public String toString() {
return this.money + "-" + this.seq;
}

@Override
public int compareTo(MoneyHouse o) {
if(this.money > o.getMoney()) {
return 1;
}else if(this.money < o.getMoney()) {
return -1;
}
return 0;
};


public static void main(String[] args) {
Map<MoneyHouse,Integer> moneyMap = new TreeMap<MoneyHouse,Integer> ();
for(int i=1; i<=10; i++) {
int v = (int)(Math.random()*100);
MoneyHouse mh = new MoneyHouse();
mh.setSeq(i);
mh.setMoney(v);
moneyMap.put(mh,i);
System.out.println( mh.toString());
}
System.out.println("=======treeMap存值后会基于key自动排序========");
for(Entry<MoneyHouse,Integer> entry:moneyMap.entrySet()) {
System.out.println(entry.getKey().toString());
}
}
}

 

 

 

operation result:----------------------------------------------- --------------------------------------

 

95-1
91-2
27-3
19-4
66-5
31-6
49-7
38-8
57-9
61-10
after ======= treeMap key value is stored automatically sorted based ==== ====
19-4
27-3
31-6
38-8
49-7
57-9
61 - 10
66-5
91-2
95-1

Guess you like

Origin www.cnblogs.com/jjunior/p/12669824.html