Java中有很多有序集合類型可供選擇,如ArrayList、LinkedList、TreeSet、LinkedHashSet、PriorityQueue等。每個集合都有它自己的特點,可以根據具體業務場景需求選取適合的集合。這篇文章將從多個方面對Java有序集合進行詳細介紹和使用。
一、ArrayList
ArrayList是Java中常用的集合之一,其內部基於數組實現,可以動態增長,同時支持隨機訪問。以下是ArrayList的簡單應用示例:
ArrayList<String> list = new ArrayList<>(); list.add("Hello"); list.add("World"); list.add("Java"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } list.remove(1); for (String str : list) { System.out.println(str); }
上面的代碼創建了一個String類型的ArrayList,並添加了3個元素。使用for循環和get方法遍歷ArrayList並輸出其內容,再使用remove方法刪掉第二個元素,最後使用增強型for循環遍歷ArrayList並輸出其內容。
二、LinkedList
LinkedList是Java中另一個常用的集合,其內部基於鏈表實現,支持動態增長和雙向訪問。以下是LinkedList的簡單應用示例:
LinkedList<Integer> list = new LinkedList<>(); list.add(1); list.add(3); list.add(5); for (int num : list) { System.out.println(num); } list.removeLast(); for (int num : list) { System.out.println(num); }
上面的代碼創建了一個Integer類型的LinkedList,並添加了3個元素。使用增強型for循環遍歷LinkedList並輸出其內容,再使用removeLast方法刪除最後一個元素,並使用增強型for循環遍歷LinkedList並輸出其內容。
三、TreeSet
TreeSet是Java中一個支持自然排序的有序Set集合,內部使用紅黑樹實現。以下是TreeSet的簡單應用示例:
TreeSet<Integer> set = new TreeSet<>(); set.add(2); set.add(4); set.add(1); for (int num : set) { System.out.println(num); } set.remove(4); for (int num : set) { System.out.println(num); }
上面的代碼創建了一個Integer類型的TreeSet,並添加了3個元素。使用增強型for循環遍歷TreeSet並輸出其內容,再使用remove方法刪除元素4,並使用增強型for循環遍歷TreeSet並輸出其內容。
四、LinkedHashSet
LinkedHashSet是Java中的有序Set集合,內部使用哈希表與鏈表實現。與TreeSet不同的是,LinkedHashSet保持元素插入的順序,而不關心元素的大小順序。以下是LinkedHashSet的簡單應用示例:
LinkedHashSet<String> set = new LinkedHashSet<>(); set.add("W"); set.add("H"); set.add("J"); for (String str : set) { System.out.println(str); } set.remove("H"); for (String str : set) { System.out.println(str); }
上面的代碼創建了一個String類型的LinkedHashSet,並添加了3個元素。使用增強型for循環遍歷LinkedHashSet並輸出其內容,再使用remove方法刪除元素”H”,並使用增強型for循環遍歷LinkedHashSet並輸出其內容。
五、PriorityQueue
PriorityQueue是Java中的一個優先隊列,其內部使用堆來實現。可以保證每次出隊的元素都是優先順序最高的,也可以指定比較器實現自定義排序規則。以下是PriorityQueue的簡單應用示例:
PriorityQueue<Integer> queue = new PriorityQueue<>(); queue.offer(3); queue.offer(5); queue.offer(1); while (!queue.isEmpty()) { System.out.println(queue.poll()); } PriorityQueue<String> strQueue = new PriorityQueue<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } }); strQueue.offer("Hello"); strQueue.offer("World"); strQueue.offer("Java"); while (!strQueue.isEmpty()) { System.out.println(strQueue.poll()); }
上面的代碼創建了一個Integer類型的PriorityQueue,並添加了3個元素。使用while循環和poll方法遍歷PriorityQueue並輸出其內容,輸出的結果是1、3、5。接著,創建了一個String類型的PriorityQueue,並使用自定義的Comparator實現了倒序排序,再使用while循環和poll方法遍歷PriorityQueue並輸出其內容,輸出的結果是World、Java、Hello。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/297526.html