HashSet add() trong java với ví dụ cụ thể

Method add() trong HashSet được dùng để thêm một phần tử vào HashSet. Method này chỉ thêm phần tử không tồn tại trước đó trong HashSet. Nếu phần tử chúng ta thêm vào đã tồn tại thì giá trị trả về là false.

Syntax:

public boolean add(Object e);

Tham số truyền vào Object e phải cùng kiểu dữ liệu với HashSet được thêm vào.

Ví dụ

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<String> h = new HashSet<String>();

        // Adding elements into HashSet usind add()
        h.add("HGA");
        h.add("SHI");
        h.add("LFD");

        System.out.println(h);
        System.out.println("Them phan tu HGA: " + h.add("HGA"));
    }
}

Output:

[HGA, SHI, LFD]
Them phan tu HGA: false

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x