天天看點

有序表 TreeMap和TreeSet

TreeMap

與哈希表HashMap的差別: 有序表組織key,哈希表完全不組織。

  • TreeMap關鍵點:放入有序表中的元素,若不是基本類型,必須要有比較器,才能使其内部有序。

基本方法

Comparator<K> com = new Comparator<Integer>(){
    @Override
    public int compare(Integer  o1, Integer o2){
      return o1 - o2; // o1.compareTo(o2); 
    }
  };
Tree<K, v> treeMap = new TreeMap<>(com);
      
方法 作用
put(K, V) 放入KV
containsKey(K) Key值中是否包含K
get(K) 擷取對應V
firstKey() 最大的數
lastKey() 最小的數
floorKey(E) 在所有 <= E的數中,離E最近的數
ceilingKey(E) 在所有 >= E的數中,離E最近的數

疊代方法(唯一)

for (Iterator it = treeMap.entrySet().iterator(); it.hasNext()){
    Map.Entry  entry = (Map.Entry)it.next();
    System.out.println(entry.getKey() + "  ->  " + entry.getValue()); 
  }
      

TreeSet

與HashSet的差別: 實作方式、是否有序、是否可放入NULL值

  1. HashSet是哈希表實作的,TreeSet是二叉樹實作的。
  2. HashSet:無序的,TreeSet:自動排序的。
  3. HashSet:可放入NULL,當且僅當一個NULL值,TreeSet:不允許NULL值。
  • TreeSet關鍵點:非基礎類型必須提供比較器
  • 擴充:HashSet是基于哈希表實作的,實作較簡單,基本調用底層HashMap的相關方法完成。

TreeSet treeSet = new TreeSet<>(new NodeComparator());

    public static class NodeComparator implements Comparator<Node> {

        @Override
        public int compare(Node o1, Node o2) {
            return o1.value - o2.value; // 類似 o1.compareTo(o2);
        }

    }
      
方法介紹
add(T) 加入元素T