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:

Java Program to Implement Hash Tables Chaining with Binary Trees
Using a Mutex Object in Java
Spring Boot - Creating Docker Image
Java Program to Generate All Possible Combinations of a Given List of Numbers
Java Program to Implement Heap Sort Using Library Functions
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Add Multiple Items to an Java ArrayList
Quick Intro to Spring Cloud Configuration
Java Program to Generate a Random Subset by Coin Flipping
Java Program to Implement Pollard Rho Algorithm
Java Program to Find a Good Feedback Edge Set in a Graph
Java Program to Perform the Unique Factorization of a Given Number
Logout in an OAuth Secured Application
Java Program to Implement Borwein Algorithm
Introduction to Java Serialization
Hướng dẫn Java Design Pattern – Null Object
Spring Data JPA Delete and Relationships
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Supplier trong Java 8
Jackson Annotation Examples
Getting Started with Forms in Spring MVC
Một số nguyên tắc, định luật trong lập trình
Java Program to Implement Fermat Primality Test Algorithm
Servlet 3 Async Support with Spring MVC and Spring Security
Write/Read cookies using HTTP and Read a file from the internet
Lớp Properties trong java
Java Program to Find the Peak Element of an Array O(n) time (Naive Method)
Giới thiệu Java 8
Queue và PriorityQueue trong Java
Configure a Spring Boot Web Application
Hướng dẫn sử dụng Java Annotation
Spring Boot - Rest Template

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.