CodeGym /Java Blog /Toto sisi /Java 中的集合
John Squirrels
等級 41
San Francisco

Java 中的集合

在 Toto sisi 群組發布

Java中的集合是什麼?

java中的集合被表示為一個容器,它將所有元素分組為一個單元。 例如,郵件資料夾(一組電子郵件)、電話簿(姓名到電話號碼的對應)。

什麼是框架?

框架是一個基本基礎或佈局,您可以在其上使用提供的不同類別和介面開始工作。 例如,Laravel 是最著名的 PHP 框架之一,它為您的應用程式提供了基本框架。

Java 中的集合框架是什麼?

所有物件都被分組為單一物件以及表示和提供操作集合的不同方法的體系結構。因此,Java 中的集合框架提供了已經實現的不同資料結構來儲存資料和方法,並透過排序、搜尋、刪除和插入等功能來操作它們。 例如,您想要為某個隨機公司實施一個系統,以基於先到先服務的原則改善其客戶的服務。這也稱為 FIFO(先進先出)實作。現在我們需要實作這個資料結構,然後用它來實現我們的目標。Collections框架為我們提供了一個Queue接口,我們只需要導入它,而不需要實作它,然後使用它,就完成了。 實作:您可以使用以下行匯入所有集合:
import java.util.*;
如果要匯入特定集合,請使用確切的套件名稱,例如:
import java.util.LinkedList;

Java 中集合框架的優點

它具有以下優點。
  1. 已經實施(節省時間)。
  2. 性能效率(速度和品質)。
  3. 減少學習和使用新 API 的工作量。

集合框架的層次結構是什麼?

現在讓我們來看看集合層次結構,但首先,我們需要了解該框架的基本元件。
  1. 介面
  2. 類別(實作)
  3. 演算法

集合框架的層次結構

Java 中的集合 - 1您的理解:
  1. Collection、Set、Queue 和 List 都是介面。Set、Queue 和 List由 Collection 介面擴充。
  2. PriorityQueue、HashSet、LinkedList 和 Stack 都是類別或這些介面的實作。
  3. 一個類別不強制只實作 一個介面。例如,LinkedList 也實作了 Deque 介面。

收藏類型

Java集合框架中有很多類型的集合來減少我們的工作量。以下是一些集合的列表:
  1. 數組列表類
  2. 鍊錶類
  3. 列表介面
  4. 設定介面
  5. 隊列介面
  6. 地圖介面
  7. 優先隊列類
  8. HashMap類
  9. 類似的介面
  10. LinkedHashMap 類
  11. 樹圖類
  12. 哈希表

集合介面

這裡我們將討論一些常見的集合接口,然後討論類別實作的一些方法。

採集介面

這是集合框架的基礎,因為它提供了所有必要的實作方法。Map 是唯一沒有實作它的資料結構,但其餘的都實作了它的方法。此介面具有用於了解集合的大小、集合中是否存在物件、從集合中新增或刪除物件的方法。

可迭代介面

它是 Collections 框架的根接口,因為它是由所有類別實現的 Collection 接口擴展的。它會傳回特定集合的迭代器以對其進行迭代。

隊列介面

佇列用於保存元素,但不能對其進行處理。實現了基本的集合操作,它還提供了額外的插入和提取方法。

設定介面

集合用於保存其中唯一的元素。它從不包含重複的元素,並對數學集合抽象進行建模來表示集合,例如機器上運行的進程。

列表介面

列表是一個有序集合,有時稱為序列,它可以在其中保存重複元素。它為使用者提供更新或刪除特定元素的控制,透過使用其整數索引值在特定點插入元素。LinkedList和ArrayList是List介面的實作類別。

雙端佇列介面

Deque代表雙端佇列,這意味著我們可以在兩端執行操作。我們可以從兩端插入和刪除元素。Deque 介面擴充了佇列介面。ArrayDeque 和 LinkedList 都實作了 Deque 介面。它提供了插入、刪除和從兩端檢查實例的方法。

地圖介面

Map 介面也是 Collections 框架的一部分,但它不會擴充 Collection 介面。它用於儲存鍵值對。它的主要實作是HashMap、TreeMap和LinkesHashMap,它們在某些方面與HashSet、TreeSet和LinkedHashSet類似。它始終包含唯一的鍵,但值可以重複。當您需要根據鍵添加、刪除或搜尋項目時,它非常有用。它為我們提供了putgetremovesizeempty等基本方法。

這些介面的常用方法

現在我們來看看這個框架中除Map介面之外的不同類別的實作所提供的一些常用方法。
方法 描述
公共布爾加法(E e) 用於向集合中插入一個元素
公共布爾刪除(物件元素) 用於從集合中刪除一個元素
公共 int 大小() 傳回集合中元素的數量
公共布爾包含(物件元素) 用於搜尋元素
公共布爾 isEmpty() 檢查集合是否為空
公共布爾等於(物件元素) 檢查平等性

集合類

眾所周知,框架有不同的接口,由其中的許多類別實現。現在我們來看看一些常用的類別。

鍊錶

它是最常用的資料結構,它實作了雙向鍊錶來儲存其中的元素。它可以儲存重複的元素。它實作了由Queue介面和List介面擴充的Dequeue介面。它不同步。現在讓我們看看如何使用 LinkedList 解決上面討論的問題(先進先出概念)。問題是以顧客到達的方式(即先進先出)為顧客提供服務。

例子

import java.util.*;

public class LinkedListExample {
    public static void main(String[] args) {
        Queue<String> customerQueue = new LinkedList<String>();
        //Adding customers to the Queue as they arrived
        customerQueue.add("John");
        customerQueue.add("Angelina");
        customerQueue.add("Brooke");
        customerQueue.add("Maxwell");

        System.out.println("Customers in Queue:"+customerQueue);
        //element() => returns head of the queue
        //we will see our first customer and serve him
        System.out.println("Head of the queue i.e first customer: "+customerQueue.element());
        //remove () method =>removes first element(customer) from the queue i.e the customer is served so remove him to see next
        System.out.println("Element removed from the queue: "+customerQueue.remove());
        //poll () => removes and returns the head
        System.out.println("Poll():Returned Head of the queue: "+customerQueue.poll());
        //print the remaining customers in the Queue
        System.out.println("Final Queue:"+customerQueue);
    }
}

輸出

佇列中的客戶:[John、Angelina、Brooke、Maxwell] 佇列頭,即第一個客戶:John 從佇列中刪除的元素:John Poll():Returned 佇列頭:Angelina 最終佇列:[Brooke、Maxwell]

數組列表

它只是實作了 List 介面。它維護插入順序並使用動態數組來儲存不同資料類型的元素。元素可以重複。它也是非同步的並且可以儲存空值。現在讓我們看看它的不同方法...當我們不知道需要插入多少記錄或元素時,這些方法很有用。讓我們舉一個圖書館的例子,我們不知道我們需要保存多少本書。所以每當我們有一本書時,我們需要將它插入到ArrayList中。

例子

public class ArrayListExample {
	public static void main(String args[]) {

		// Creating the ArrayList
		ArrayList<String> books = new ArrayList<String>();

		// Adding a book to the list
		books.add("Absalom, Absalom!");
		// Adding a book in array list
		books.add("A Time to Kill");
		// Adding a book to the list
		books.add("The House of Mirth");
		// Adding a book to the list
		books.add("East of Eden");
		// Traversing the list through Iterator
		Iterator<String> itr = books.iterator();
		while (itr.hasNext()) {
			System.out.println(itr.next());
		}
	}
}

輸出

押沙龍,押沙龍!殺死伊甸園東歡樂屋的時刻

哈希集

它實作 Set 介面並且從不包含重複值。它實現了用於存儲值的哈希表。它還允許空值。它從不維護插入順序,但為addremovesizecontains方法提供恆定的時間效能。最適合搜尋操作,且不同步。

例子

import java.util.*;
class HashSetExample{
    public static void main(String args[]){
        //creating HashSet and adding elements to it
        HashSet<Integer> hashSet=new HashSet();
        hashSet.add(1);
        hashSet.add(5);
        hashSet.add(4);
        hashSet.add(3);
        hashSet.add(2);
        //getting an iterator for the collection
        Iterator<Integer> i=hashSet.iterator();
        //iterating over the value
        while(i.hasNext())  {
            System.out.println(i.next());
        }
    }
}

輸出

1 2 3 4 5
如您所見,它不維護插入順序。

數組雙端隊列

它實現了 Deque 接口,因此允許從兩端進行操作。它不允許空值。當實作為 Stack 和 LinkedList 時,它比 Stack 和 LinkedList 更快。ArrayDeque 沒有大小限制,因為它可以根據要求增長和縮小。它是不同步的,這意味著它不是線程安全的。為了保持線程安全,我們必須實作一些外部邏輯。

例子

import java.util.*;
public class ArrayDequeExample {
   public static void main(String[] args) {
       //creating Deque and adding elements
       Deque<String> deque = new ArrayDeque<String>();
       //adding an element
       deque.add("One");
       //adding an element at the start
       deque.addFirst("Two");
       //adding an element at the end
       deque.addLast("Three");
       //traversing elements of the collection
       for (String str : deque) {
            System.out.println(str);
       }
   }
}

輸出

二一三

哈希映射

它是哈希表支援的 Map 介面的實作。它儲存鍵值對。它不允許空值。它不同步。它從不保證插入順序。它為getput等方法提供恆定的時間性能。其性能取決於兩個因素—初始容量負載係數。容量是哈希表中儲存桶的數量,因此初始容量是建立時分配的儲存桶的數量。負載因子是衡量哈希表在容量增加之前可以填入多少內容的指標。rehash方法用於增加容量,主要是桶數加倍。

例子

import java.util.*;
public class HashMapExample{
    public static void main(String args[]){
        //creating a HashMap
        HashMap<Integer,String> map=new HashMap<Integer,String>();
        //putting elements into the map
        map.put(1,"England");
        map.put(2,"USA");
        map.put(3,"China");

        //get element at index 2
        System.out.println("Value at index 2 is: "+map.get(2));
        System.out.println("iterating map");
        //iterating the map
        for(Map.Entry m : map.entrySet()){
            System.out.println(m.getKey()+" "+m.getValue());
        }
    }
}

輸出

索引 2 處的值為:中國迭代地圖 1 英國 2 美國 3 中國

演算法

Collections框架為我們提供了不同的演算法來將不同的操作應用於集合。這裡我們將看看這些演算法涵蓋了哪些主要操作。它包含與以下相關的演算法:
  1. 排序
  2. 搜尋中
  3. 洗牌
  4. 常規數據操作
  5. 作品
  6. 尋找極端值
為了更好地理解,我們將討論排序演算法。

排序

排序演算法根據排序關係對清單進行重新排序。提供了兩種形式的關係。
  1. 自然排序
  2. 比較訂購

自然排序

在自然排序中,列表根據其元素進行排序。

比較訂購

在這種排序形式中,附加參數(比較器)與列表一起傳遞。使用稍微優化的合併排序演算法進行排序,該演算法快速且穩定,因為它保證了 n log(n) 運行時間,並且不會對相等的元素進行重新排序。我們將使用 ArrayList 中的相同範例來示範排序。

例子

import java.util.*;
public class SortingExample{
    public static void main(String args[]){
        //Creating arraylist
        ArrayList<String> books=new ArrayList<String>();
        //Adding a book to the arraylist
        books.add("A Time to Kill");
        //Adding a book to the arraylist
        books.add("Absalom, Absalom!");
        //Adding a book to the arraylist
        books.add("The House of Mirth");
        //Adding a book to the arraylist
        books.add("East of Eden");
        //Traversing list through Iterator before sorting
        Iterator itrBeforeSort=books.iterator();
        while(itrBeforeSort.hasNext()){
            System.out.println(itrBeforeSort.next());
        }
        //sorting the books
        Collections.sort(books);
        System.out.println("After sorting the books");
        //Traversing list through Iterator after sorting
        Iterator itr=books.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
}

輸出

殺押沙龍的時刻到了,押沙龍!伊甸園東邊的歡樂屋 在整理書籍後,殺死押沙龍的時刻,押沙龍!伊甸園之東歡樂之家

結論

我們希望現在您了解什麼是java集合框架,它的介面和類別是什麼以及如何實現它的不同類別。您始終可以使用此框架來減少 Java 方面的工作量。請隨意練習,並在需要更多幫助時返回此處。快樂學習!
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION