🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Java 中的`LinkedHashSet`类 > 原文: [https://beginnersbook.com/2013/12/linkedhashset-class-in-java-with-example/](https://beginnersbook.com/2013/12/linkedhashset-class-in-java-with-example/) 之前我们已经在[`HashSet`](https://beginnersbook.com/2013/12/hashset-class-in-java-with-example/)和[`TreeSet`](https://beginnersbook.com/2013/12/treeset-class-in-java-with-example/)上分享了教程。[`LinkedHashSet`](https://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html)也是`Set`接口的一个实现,它类似于`HashSet`和`TreeSet`,除了下面提到的差异: 1. `HashSet`不保持其元素的任何顺序。 2. `TreeSet`按升序对元素进行排序。 3. `LinkedHashSet`保持插入顺序。元素按照添加到`Set`中的相同顺序进行排序。 ## `LinkedHashSet`的示例: ```java import java.util.LinkedHashSet; public class LinkedHashSetExample { public static void main(String args[]) { // LinkedHashSet of String Type LinkedHashSet<String> lhset = new LinkedHashSet<String>(); // Adding elements to the LinkedHashSet lhset.add("Z"); lhset.add("PQ"); lhset.add("N"); lhset.add("O"); lhset.add("KK"); lhset.add("FGH"); System.out.println(lhset); // LinkedHashSet of Integer Type LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>(); // Adding elements lhset2.add(99); lhset2.add(7); lhset2.add(0); lhset2.add(67); lhset2.add(89); lhset2.add(66); System.out.println(lhset2); } } ``` **输出:** ```java [Z, PQ, N, O, KK, FGH] [99, 7, 0, 67, 89, 66] ``` 观察输出:两种类型的`LinkedHashSet`都保留了插入顺序。