Giao diện Java SortedSet: 344
Giao diện Java SortedSet
Trong hướng dẫn này, chúng ta sẽ tìm hiểu về giao diện SortedSet trong Java và các phương thức của nó với sự trợ giúp của một ví dụ.
Các SortedSet
giao diện của khuôn khổ Java Collections được sử dụng để lưu trữ các yếu tố với một số thứ tự trong một bộ.
Nó mở rộng giao diện Đặt .
Lớp triển khai SortedSet
Để sử dụng các chức năng của SortedSet
giao diện, chúng ta cần sử dụng TreeSet
lớp triển khai nó.
Làm thế nào để sử dụng SortedSet?
Để sử dụng SortedSet
, chúng ta phải nhập java.util.SortedSet
gói trước.
// SortedSet implementation by TreeSet class
SortedSet<String> animals = new TreeSet<>();
Chúng tôi đã tạo một tập hợp được sắp xếp có tên là động vật bằng cách sử dụng TreeSet
lớp.
Ở đây chúng tôi không sử dụng đối số nào để tạo một tập hợp được sắp xếp. Do đó tập hợp sẽ được sắp xếp một cách tự nhiên.
Các phương thức của SortedSet
Các SortedSet
giao diện bao gồm tất cả các phương pháp của giao diện Set . Đó là vì Set
là một giao diện siêu của SortedSet
.
Bên cạnh các phương thức có trong Set
giao diện, SortedSet
giao diện cũng bao gồm các phương thức sau:
- comparator() – returns a comparator that can be used to order elements in the set
- first() – returns the first element of the set
- last() – returns the last element of the set
- headSet(element) – returns all the elements of the set before the specified element
- tailSet(element) – returns all the elements of the set after the specified element including the specified element
- subSet(element1, element2) – returns all the elements between the element1 and element2 including element1
Triển khai SortedSet trong lớp TreeSet
import java.util.SortedSet;
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
// Creating SortedSet using the TreeSet
SortedSet<Integer> numbers = new TreeSet<>();
// Insert elements to the set
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("SortedSet: " + numbers);
// Access the element
int firstNumber = numbers.first();
System.out.println("First Number: " + firstNumber);
int lastNumber = numbers.last();
System.out.println("Last Number: " + lastNumber);
// Remove elements
boolean result = numbers.remove(2);
System.out.println("Is the number 2 removed? " + result);
}
}
Đầu ra
SortedSet: [1, 2, 3, 4] First Number: 1 Last Number: 4 Is the number 2 removed? true
Để tìm hiểu thêm TreeSet
, hãy truy cập Java TreeSet .
Bây giờ chúng ta đã biết về SortedSet
giao diện, chúng ta sẽ tìm hiểu về cách triển khai của nó bằng cách sử dụng TreeSet
lớp.