hashset-java

HashSet trong Java

Lớp HashSet trong java là một lớp kế thừa lớp AbstractSet và triển khai của Set Interface trong Collections Framework nên nó sẽ có một vài đặc điểm và phương thức tương đồng với Set. HashSet được sử dụng để tạo một bộ sưu tập sử dụng bảng băm để lưu trữ. Nó kế thừa lớp AbstractSet và triển khai Set interface.

Một hash table lưu giữ thông tin bởi sử dụng một kỹ thuật được gọi là hashing (băm). Trong hashing, nội dung mang tính thông tin của một key được sử dụng để quyết định một value duy nhất, được gọi là hash code của nó.

Hash code sau đó được sử dụng như là index, tại đó dữ liệu mà liên kết với key được lưu giữ. Phép biến đổi của key vào trong hash code của nó được thực hiện tự động.


Đoạn mã dưới đây hiển thị tất cả các ví dụ sử dụng các hàm tạo HashSet này.

Set<String> set = new HashSet<>();

//initial capacity should be power of 2
set = new HashSet<>(32); 

//setting backing HashMap initial capacity and load factor
set = new HashSet<>(32, 0.80f);

//creating HashSet from another Collection
Set<String> set1 = new HashSet<>(set);
Set<String> set2 = new HashSet<>(new ArrayList<>());Code language: PHP (php)

Các phương thức HashSet trong Java

MethodDescription
boolean add(Object element)Nó được sử dụng để chèn các phần tử vào HashSet.
boolean addAll(Collection c)Nó được sử dụng để chèn tất cả các phần tử của c vào HashSet.
void clear()Xóa tất cả các phần tử khỏi HashSet.
boolean contains(Object element)Trả về true nếu tập hợp này chứa phần tử đã chỉ định.
boolean containsAll(Collection c)Trả về true nếu HashSet chứa tất cả các phần tử của collection c đã chỉ định.
boolean equals(Object o)So sánh các đối tượng được chỉ định với HashSet.
boolean isEmpty()Trả về true nếu HashSet không chứa phần tử.
int hashCode()Trả về giá trị mã băm
Iterator iterator()Trả về một trình vòng lặp iterator để duyệt qua các phần tử của HashSet.
boolean remove(Object o)Xóa phần tử đã chỉ định khỏi HashSet.
boolean removeAll(Collection c)Xóa khỏi HashSet tất cả các phần tử của nó được chứa trong collection c đã chỉ định.
boolean retainAll(Collection c)Chỉ giữ lại các phần tử trong HashSet được chứa trong collection c đã chỉ định.
int size()Trả về số lượng các phần tử của HashSet.
Object[] toArray()Trả về một mảng chứa tất cả các phần tử trong HashSet.
T[] toArray(T[] a)Trả về một mảng chứa tất cả các phần tử trong HashSet, kiểu run-time của mảng trả về là kiểu đã chỉ định.

Ví dụ HashSet trong Java

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class HashSetExample {

	public static void main(String[] args) {

		Set<String> fruits = new HashSet<>();
		
		//add example
		fruits.add("Apple");
		fruits.add("Banana");
		
		//isEmpty example
		System.out.println("fruits set is empty = "+fruits.isEmpty());

		//contains example
		System.out.println("fruits contains Apple = "+fruits.contains("Apple"));
		System.out.println("fruits contains Mango = "+fruits.contains("Mango"));
		
		//remove example
		System.out.println("Apple removed from fruits set = "+fruits.remove("Apple"));
		System.out.println("Mango removed from fruits set = "+fruits.remove("Mango"));
		
		//size example
		System.out.println("fruits set size = "+fruits.size());
		
		//addAll example
		List<String> list = new ArrayList<>(); 
		list.add("Apple"); list.add("Apple"); 
		list.add("Banana"); list.add("Mango");
		
		System.out.println("fruits set before addAll = "+fruits);
		System.out.println("list = "+list);
		fruits.addAll(list);
		System.out.println("fruits set after addAll = "+fruits);

		//iterator example
		Iterator<String> iterator = fruits.iterator();
		while(iterator.hasNext()){
			System.out.println("Consuming fruit "+iterator.next());
		}
		
		//removeAll example
		fruits.add("Orange");
		System.out.println("fruits set before removeAll = "+fruits);
		System.out.println("list = "+list);
		fruits.removeAll(list);
		System.out.println("fruits set after removeAll = "+fruits);
		
		//clear example
		fruits.clear();
		System.out.println("fruits set is empty = "+fruits.isEmpty());

	}

}
Code language: PHP (php)

Output:

fruits set is empty = false
fruits contains Apple = true
fruits contains Mango = false
Apple removed from fruits set = true
Mango removed from fruits set = false
fruits set size = 1
fruits set before addAll = [Banana]
list = [Apple, Apple, Banana, Mango]
fruits set after addAll = [Apple, Mango, Banana]
Consuming fruit Apple
Consuming fruit Mango
Consuming fruit Banana
fruits set before removeAll = [Apple, Mango, Orange, Banana]
list = [Apple, Apple, Banana, Mango]
fruits set after removeAll = [Orange]
fruits set is empty = trueCode language: PHP (php)

Ví dụ HashSet ConcurrentModificationException

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetConcurrentModificationExceptionExample {

	public static void main(String[] args) {
		Set<String> fruits = new HashSet<>();
		
		//add example
		fruits.add("Apple");
		fruits.add("Banana");
		fruits.add("Orange");
		fruits.add("Mango");
		
		Iterator<String> iterator = fruits.iterator();
		
		while(iterator.hasNext()){
			String fruit = iterator.next();
			System.out.println("Processing "+fruit);
			
			//wrong way of removing from Set, can throw java.util.ConcurrentModificationException
			if("Orange".equals(fruit)) fruits.remove("Orange");
		}
	}

}Code language: JavaScript (javascript)

Output:

Processing Apple
Processing Mango
Processing Orange
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
	at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
	at com.journaldev.examples.HashSetConcurrentModificationExceptionExample.main(HashSetConcurrentModificationExceptionExample.java:21)Code language: PHP (php)

Ví dụ HashSet to Array

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class HashSetToArrayExample {

	public static void main(String[] args) {
		Set<Integer> ints = new HashSet<>();
		for(int i=0; i<10; i++){
			ints.add(i);
		}
		System.out.println("ints set = "+ints);
		
		// set to array example
		Integer[] intArray = new Integer[ints.size()];
		intArray = ints.toArray(intArray);
		System.out.println("intArray = "+Arrays.toString(intArray));
		ints.remove(0);ints.remove(1);
		System.out.println("intArray = "+Arrays.toString(intArray));
		
		
		//array to set example
		ints = new HashSet<>(Arrays.asList(intArray));
		System.out.println("ints from array = "+ints);
		ints.remove(0);ints.remove(1);
		System.out.println("ints from array after remove = "+ints);
		System.out.println("intArray = "+Arrays.toString(intArray));


	}

}Code language: JavaScript (javascript)

Output:

ints set = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
intArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
intArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ints from array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ints from array after remove = [2, 3, 4, 5, 6, 7, 8, 9]
intArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]Code language: PHP (php)

Tổng kết

Lưu ý rằng HashSet có thể kiểm tra bản sao khi chúng ta cố gắng thêm một phần tử. Nhưng chúng ta có thể thay đổi các giá trị đối tượng bằng cách sử dụng các phương thức setter và làm cho nó trùng lặp. Nó hoạt động vì không có thao tác nào được thực hiện trên Set. Đây là lý do tại sao các đối tượng Immutable hoạt động tốt hơn với Set và Map.

Đó là tất cả về hướng dẫn ví dụ về HashSet trong Java, tôi hy vọng rằng tất cả những điều quan trọng đều được đề cập đến đối với HashSet trong Java. Nếu tôi có thiếu sót gì, vui lòng cho tôi biết thông qua các bình luận và tôi cũng sẽ cố gắng bổ sung thêm.

Bài viết liên quan

Trả lời

Email của bạn sẽ không được hiển thị công khai.

Tài liệu + Khóa học lập trình FREE
Tài liệu + Khóa học lập trình FREE

DMCA.com Protection Status