Set Interface trong Java

Set (tập hợp) trong Java là một Interface, được kế thừa từ Interface Collection. Set không chứa các phần tử trùng nhau.

Interface java.util.Set được định nghĩa như sau:

public interface Set<E> extends Collection<E> 

Các phương thức của Set interface

Phương thứcMô tả
public boolean add(Object element)Thêm một phần tử vào collection.
public boolean addAll(Collection c)Thêm các phần tử collection được chỉ định vào collection gọi phương thức này.
public boolean remove(Object element)Xóa phần tử ra khỏi collection.
public boolean removeAll(Collection c)Xóa tất cả các phần tử từ collection được chỉ định ra khỏi collection gọi phương thức này.
public boolean retainAll(Collection c)Xóa tất cả các thành phần từ collection gọi phương thức này ngoại trừ collection được chỉ định.
public int size()Trả về tổng số các phần tử trong collection.
public void clear()Xóa tất cả các phần tử trong Collection, sau khi thực hiện phương thức này, Collection sẽ rỗng (empty)
public boolean contains(Object element)Kiểm tra một phần tử có nằm trong Collection không
public boolean containsAll(Collection c)Kiểm tra một Collection có chứa tất cả các phần tử của một Collection khác
public Iterator iterator()Trả về một iterator.
public Object[] toArray()Chuyển đổi collection thành mảng (array).
public boolean isEmpty()Kiểm tra Collection có rỗng hay không.
public boolean equals(Object element)So sánh 2 collection.
public int hashCode()Trả về số hashcode của collection.

Ví dụ:

import java.util.HashSet;
import java.util.Set;
 
public class SetExample {
    public static void main(String[] args) {
        // Create set
        Set<String> items = new HashSet<>();
        items.add("A02"); // Add new item
        items.add("D03"); 
        items.add("D03"); // item is ignored
        items.add("01");
        items.add("04");
 
        // Show set through for-each
        for (String item: items) {
            System.out.print(item + " ");
        }
    }
}

Kết quả thực thi chương trình trên:

01 A02 04 D03 

Trong ví dụ trên, Item D03 thêm lần thứ 2 bị bỏ qua, bởi vì nó đã tồn tại trong items, thứ tự các phần tử được thêm vào không hiển thị đúng thứ tự, do chúng ta sử dụng HashSet. Để giữ đúng thứ tự thêm vào chúng ta có thể sử dụng LinkedHashSet, hoặc sử dụng TreeSet để thêm các phần tử vào tập hợp được sắp xếp. Tôi sẽ giới thiệu chi tiết với các bạn các tập hợp (Set) này ở các bài viết tiếp theo.

Cám ơn các bạn đã quan tâm và theo dõi bài viết. Hẹn gặp lại ở bài viết tiếp theo.

Related posts:

Hướng dẫn Java Design Pattern – Flyweight
Java Program to Implement HashMap API
Fixing 401s with CORS Preflights and Spring Security
Java Program to Implement ConcurrentLinkedQueue API
Biến trong java
Java Program to find the maximum subarray sum using Binary Search approach
Sending Emails with Java
Java Program to Implement VList
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Java Program to Implement HashTable API
Getting Started with Stream Processing with Spring Cloud Data Flow
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
Simultaneous Spring WebClient Calls
Java Program to implement Bi Directional Map
Mảng (Array) trong Java
Spring Boot - Sending Email
Autoboxing và Unboxing trong Java
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Java Program to Implement Interpolation Search Algorithm
Java Program to Perform the Shaker Sort
Java Program to Implement Brent Cycle Algorithm
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Template Engines for Spring
Guide to Spring 5 WebFlux
Java Program to Implement Max-Flow Min-Cut Theorem
Spring 5 Functional Bean Registration
OAuth2.0 and Dynamic Client Registration
Java Program to Implement LinkedHashMap API
Java Program to Solve TSP Using Minimum Spanning Trees
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Java Program to Implement Variable length array

3 Trackbacks / Pingbacks

  1. HashSet trong java – Blog của VietMX
  2. LinkedHashSet trong java – Blog của VietMX
  3. TreeSet và sử dụng Comparable, Comparator trong java – Blog của VietMX

Comments are closed.