java集合 TreeMap 使用自然排序和定製排序
阿新 • • 發佈:2019-02-17
import java.util.Comparator; import java.util.TreeMap; public class Demo3 { public static void main(String[] args) { System.out.println("使用自然排序:"); TreeMap<IdNumber2, String> treeMap=new TreeMap<IdNumber2,String>(); treeMap.put(new IdNumber2(1000), "王尼瑪"); treeMap.put(new IdNumber2(1001), "萬尼瑪"); treeMap.put(new IdNumber2(1002), "藍尼瑪"); treeMap.put(new IdNumber2(1003), "馮尼瑪"); treeMap.put(new IdNumber2(1004), "秦尼瑪"); System.out.println("treeMap="+treeMap); System.out.println("使用定製排序:(從小到大排序)"); //使用釘子排序,指明比較器 TreeMap<IdNumber2, String> treeMap2= new TreeMap<IdNumber2,String>(new MyComparatorBigToSmall()); treeMap2.put(new IdNumber2(1000), "王尼瑪"); treeMap2.put(new IdNumber2(1001), "萬尼瑪"); treeMap2.put(new IdNumber2(1002), "藍尼瑪"); treeMap2.put(new IdNumber2(1003), "馮尼瑪"); treeMap2.put(new IdNumber2(1004), "秦尼瑪"); System.out.println("treeMap2="+treeMap2); System.out.println("使用定製排序:(從大到小排序)"); TreeMap<IdNumber2, String> treeMap3= new TreeMap<IdNumber2,String>(new MyComparatorSmallToBig()); treeMap3.put(new IdNumber2(1000), "王尼瑪"); treeMap3.put(new IdNumber2(1001), "萬尼瑪"); treeMap3.put(new IdNumber2(1002), "藍尼瑪"); treeMap3.put(new IdNumber2(1003), "馮尼瑪"); treeMap3.put(new IdNumber2(1004), "秦尼瑪"); System.out.println("treeMap2="+treeMap3); } } //自定義比較器:實現comparator介面 class MyComparatorBigToSmall implements Comparator<IdNumber2> //使用泛型 { @Override public int compare(IdNumber2 o1, IdNumber2 o2) { // TODO Auto-generated method stub return o1.getIdNumber()-o2.getIdNumber();//從小到大排序 } } class MyComparatorSmallToBig implements Comparator<IdNumber2> { @Override public int compare(IdNumber2 o1, IdNumber2 o2) { // TODO Auto-generated method stub return o2.getIdNumber()-o1.getIdNumber();//從小到大排序 } } //z作為鍵的類實現Comparable介面 class IdNumber2 implements Comparable<IdNumber2> { //成員屬性 private int IdNumber; public int getIdNumber() { return IdNumber; } //建構函式 public IdNumber2() { // TODO Auto-generated constructor stub } //建構函式 public IdNumber2(int IdNumber) { this.IdNumber=IdNumber; } //重寫toString()方法 @Override public String toString() { // TODO Auto-generated method stub return "["+this.IdNumber+"]"; } //重寫equals()方法 @Override public boolean equals(Object obj) { if(obj==this)//自己和自己比較 return true;//那就是同一個相等了 //傳入的引用不為空,而且兩個的型別一樣 if(obj!=null&&obj.getClass()==this.getClass()) { IdNumber2 idNumber2=(IdNumber2) obj;//型別轉換 return this.IdNumber==idNumber2.IdNumber; //如果兩個的編號一樣,那就認為相等 } return false; } //重寫hashCode()方法 @Override public int hashCode() { // TODO Auto-generated method stub return this.IdNumber*100; } //重寫compareTo()方法實現自然排序 @Override public int compareTo(IdNumber2 o) { // TODO Auto-generated method stub //return this.IdNumber-o.IdNumber;//從小到大排序: return o.IdNumber-this.IdNumber;//從大到小排序 } }