Home >Java >javaTutorial >SET
Java Set Detailed Explanation: The collection of the unique element of the unique element
This article will explore the SET interfaces and its main implementation classes in Java to help you understand how to efficiently handle the collection of duplicate elements.
SET interface is a collection that does not allow duplicate elements. It is based on a collection of mathematical operations (collections, intersections, and differences), which is very suitable for the need to ensure the uniqueness of the element.
Main features:
No duplicate elements are allowed.
<.> 2.1 hashset
Features: Based on the hash table implementation, the order of element is not guaranteed. The average time complexity of adding, deleting and finding operations is O (1), allowing a vacancy.
Applicable scenarios:<code class="language-java">import java.util.HashSet; import java.util.Set; public class HashSetExample { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Orange"); set.add("Apple"); // 重复元素,不会添加 System.out.println(set); // 元素顺序不确定 } }</code>
Applicable scenarios: Scenes that need to be predicted in the order of the iterative order.
Applicable scenarios: Elements that need to be automatically sorted, and you need to sort the scenes of efficient sorting operations.
<code class="language-java">import java.util.LinkedHashSet; import java.util.Set; public class LinkedHashSetExample { public static void main(String[] args) { Set<String> set = new LinkedHashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Orange"); System.out.println(set); // 保持插入顺序 } }</code>
<.> 3. Different set of implementation class comparison
<code class="language-java">import java.util.TreeSet; import java.util.Set; public class TreeSetExample { public static void main(String[] args) { Set<String> set = new TreeSet<>(); set.add("Apple"); set.add("Banana"); set.add("Orange"); System.out.println(set); // 元素按字母顺序排序 } }</code>Allow duplicate elements and keep the insertion order.
Queue: Follow the principle of advanced first (FIFO) for sequential treatment.
The above is the detailed content of SET