在Java中使用LinkedHashSet及示例
LinkedHashSet 是HashSet的有序版本,它在所有元素上维护一个双向链表。当需要维护迭代顺序时,使用此类。在遍历HashSet时,顺序是不可预测的,而使用LinkedHashSet可以按照插入顺序迭代元素。使用迭代器循环遍历LinkedHashSet时,元素将按照插入的顺序返回。
LinkedHashSet的层次结构如下:

参数: 此集合所维护的元素的类型
**所有实现的接口如下:**
Serializable
Cloneable,
Iterable<E>
Collection<E>
Set<E>
语法: 声明
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable
- 仅包含唯一元素,就像HashSet一样。它扩展了HashSet类并实现了Set接口。
- 维护插入顺序。
LinkedHashSet类的构造函数
1.LinkedHashSet(): 此构造函数用于创建默认的HashSet。
LinkedHashSet<E> hs = new LinkedHashSet<E>();
2.LinkedHashSet(Collection C): 用于使用集合C的元素初始化HashSet。
LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c);
3.LinkedHashSet(int size): 用于将LinkedHashSet的大小初始化为参数中提到的整数。
LinkedHashSet<E> hs = new LinkedHashSet<E>(int size);
4.LinkedHashSet(int capacity, float fillRatio): 可用于使用参数中提到的参数初始化LinkedHashSet的容量和填充比率。当元素数量超过哈希集的容量时,将使用填充比率乘以哈希集的容量,从而扩展LinkedHashSet的容量。
LinkedHashSet<E> hs = new LinkedHashSet<E>(int capacity, int fillRatio);
示例:
// Java Program to Remove Elements from LinkedHashSet
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
// RemovingElementsFromLinkedHashSet
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty LinkedHashSet
LinkedHashSet<String> hs = new LinkedHashSet<String>();
// Adding elements to above Set
// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
// Displaying Set without removing any element
System.out.println("Initial LinkedHashSet : " + hs);
// Removing "Geeks" from the Set
hs.remove("Geeks");
// Displaying Set after removing the element
System.out.println("LinkedHashSet after removing Geeks:"
+ hs);
}
}
输出:
Initial LinkedHashSet : [Geek, For, Geeks]
LinkedHashSet after removing Geeks:[Geek, For]
Operation 3: Checking for the Element Presence
In order to check whether a particular element exists in the LinkedHashSet or not, we can use the contains() method.
示例:
// Java Program to check the presence of
// an element in the LinkedHashSet
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
// CheckingElementsPresenceLinkedHashSet
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty LinkedHashSet
LinkedHashSet<String> hs = new LinkedHashSet<String>();
// Adding elements to above Set
// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
// Displaying Set elements
System.out.println("Initial LinkedHashSet : " + hs);
// Check if "Geek" exists in the Set
System.out.println("Does the Set contains 'Geek'? "
+ hs.contains("Geek"));
// Check if "For" doesn't exists in the Set
System.out.println(
"Does the Set contains 'For'? "
+ hs.contains("For"));
}
}
输出:
Initial LinkedHashSet : [Geek, For, Geeks]
Does the Set contains 'Geek'? true
Does the Set contains 'For'? true
Operation 4: Iterating Elements
In order to iterate over the LinkedHashSet, we can use the for-each loop or the iterator() method.
示例:
// Java Program to iterate through
// the LinkedHashSet
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
// IteratingThroughLinkedHashSet
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty LinkedHashSet
LinkedHashSet<String> hs = new LinkedHashSet<String>();
// Adding elements to above Set
// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
// Displaying Set elements
System.out.println("Original LinkedHashSet : " + hs);
// Iterating over Set in Java 8
System.out.println("Iterating through Set using forEach() method:");
hs.forEach(System.out::println);
// Iterating over Set using Iterator
System.out.println("Iterating through Set using Iterator:");
Iterator it = hs.iterator();
while (it.hasNext())
System.out.println(it.next());
}
}
Output: **
Original LinkedHashSet : [Geek, For, Geeks]
Iterating through Set using forEach() method:
Geek
For
Geeks
Iterating through Set using Iterator:
Geek
For
Geeks
Operation 5: Clearing the LinkedHashSet
In order to remove all the elements from the LinkedHashSet, we can use the clear() method.
示例:
// Java Program to clear the elements from LinkedHashSet
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
// ClearingLinkedHashSet
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty LinkedHashSet
LinkedHashSet<String> hs = new LinkedHashSet<String>();
// Adding elements to above Set
// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
// Displaying Set elements
System.out.println("Original LinkedHashSet : " + hs);
// Clearing Set
hs.clear();
// Displaying Set elements after clearing
System.out.println(
"LinkedHashSet after clearing all elements : " + hs);
}
}
输出:
Original LinkedHashSet : [Geek, For, Geeks]
LinkedHashSet after clearing all elements : []
// 从LinkedHashSet中删除元素的Java程序
// 导入所需的类
import java.io.*;
import java.util.*;
// 主类
// RemoveElementsFromLinkedHashSet
class GFG {
// 主驱动程序
public static void main(String[] args)
{
// 创建一个空的字符串类型的LinekdhashSet
LinkedHashSet<String> hs
= new LinkedHashSet<String>();
// 使用add()方法将元素添加到上述集合
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");
// 将所有上述元素打印到控制台
System.out.println("Initial HashSet " + hs);
// 从上面的集合中删除元素
hs.remove("B");
// 再次删除元素
System.out.println("After removing element " + hs);
// 如果元素不存在则返回false
System.out.println(hs.remove("AC"));
}
}
输出:
Initial HashSet [Geek, For, Geeks, A, B, Z]
After removing element [Geek, For, Geeks, A, Z]
false
操作3:
通过迭代LinkedHashSet
使用iterator()方法遍历LinkedHashSet的元素。最常见的方法是使用增强的for循环。
示例:
// Java程序演示迭代LinkedHashSet
// 导入所需的类
import java.io.*;
import java.util.*;
// 主类
// IteratingLinkedHashSet
class GFG {
// 主驱动程序
public static void main(String[] args)
{
// 实例化Set对象
// 因为LinkedHashSet实现了Set
// Set指向LinkedHashSet
Set<String> hs = new LinkedHashSet<String>();
// 使用add()方法将元素添加到上述集合
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");
// 使用迭代器遍历LinkedHashSet
Iterator itr = hs.iterator();
while (itr.hasNext())
System.out.print(itr.next() + ", ");
// 新行
System.out.println();
// 使用增强for循环遍历
for (String s : hs)
System.out.print(s + ", ");
System.out.println();
}
}
输出:
Geek, For, Geeks, A, B, Z,
Geek, For, Geeks, A, B, Z,
LinkedHashSet的方法
这里, E 是存储的元素类型。
| 方法 | 描述 |
|---|---|
| spliterator() | 在此集合中的元素上创建一种后期绑定和快速失败的Spliterator。 |
在类java.util.AbstractSet中声明的方法
| 方法 | 描述 |
|---|---|
| equals(Object o) | 将指定对象与此集合进行比较以判断它们是否相等。 |
| hashCode() | 返回此集合的哈希代码值。 |
| removeAll(Collection c) | 删除此集合中包含在指定collection中的所有元素(可选操作)。 |
在类java.util.AbstractCollection中声明的方法
| 方法 | 描述 |
|---|---|
| add(E e) | 如果此 set 中尚未包含指定元素,则添加指定元素(可选操作)。 |
| addAll(Collection extends E> c) | 将指定集合中的所有元素添加到此集合中(可选操作)。 clear() | 从此 set 中移除所有元素。 contains(Object o) | 如果此 set 包含指定元素,则返回 true。 containsAll(Collection> c) |
如果此集合包含指定集合中的所有元素,则返回 true。 |
| isEmpty() | 如果此 set 不包含任何元素,则返回 true。 |
| iterator() | 返回此 set 中元素的迭代器。 |
| remove(Object o) | 从此 set 中移除指定元素(如果存在)。 |
| removeAll(Collection> c) | 移除此集合中那些也包含在指定集合中的所有元素(可选操作)。 removeIf(Predicate super E> filter) | 移除符合给定谓词的此集合的所有元素。 retainAll(Collection> c) |
仅保留此集合中包含在指定集合中的元素(可选操作)。 |
| size() | 返回此 set 中的元素数(set 的基数)。 |
| toArray() | 返回包含此 collection 中所有元素的数组。 |
| toArray(T[] a) | 将此 collection 中所有元素复制到指定的数组中,运行时类型为该数组的类型。 |
Methods declared in interface java.lang.Iterable
| 方法 | 描述 |
|---|---|
| forEach(Consumer super T> action) | 对 Iterable 的每个元素执行给定的操作,直到所有元素都已被处理或操作引发异常。
### Methods declared in class java.util.HashSet 方法 | 描述 ### Methods declared in interface java.util.Collection 方法 | 描述 ### Methods declared in interface java.util.Set 方法 | 描述 |
如果此集合包含指定集合中的所有元素,则返回 true。 |
| isEmpty() | 如果此 set 不包含任何元素,则返回 true。 |
| iterator() | 返回此 set 中元素的迭代器。 |
| remove(Object o) | 从此 set 中移除指定元素(如果存在)。 |
| removeAll(Collection> c) | 移除此集合中那些也包含在指定集合中的所有元素(可选操作)。 retainAll(Collection> c) |
仅保留此集合中包含在指定集合中的元素(可选操作)。 |
| size() | 返回此 set 中的元素数(set 的基数)。 |
| toArray() | 返回包含此 collection 中所有元素的数组。 |
| toArray(T[] a) | 将此 collection 中所有元素复制到指定的数组中,运行时类型为该数组的类型。 |
| 方法 | 描述 |
|---|---|
| add(element) | 此方法用于将指定元素添加到集合中。如果集合中已经存在指定元素,则该函数仅在元素不存在时添加元素,否则返回False。 |
| addAll(Collection c) | 此方法用于将指定集合中的所有元素追加到现有集合中,元素的添加顺序随机而不具有特定顺序。 |
| clear() | 此方法用于删除集合中的所有元素,但不删除集合。集合的引用仍然存在。 |
| contains(element) | 此方法用于检查集合中是否存在指定元素。 |
| containsAll(Collection c) | 此方法用于检查集合中是否包含给定集合中的所有元素。如果集合包含所有元素,则此方法返回true,否则返回false。 |
| hashCode() | 此方法用于获取此Set实例的hashCode值。它返回一个整数值,该值是Set实例的hashCode值。 |
| isEmpty() | 此方法用于检查集合是否为空。 |
| iterator() | 此方法用于返回集合的迭代器。集合中的元素以随机顺序返回。 |
| remove(element) | 此方法用于从集合中删除指定元素。如果集合中找到指定元素,则此方法返回True,否则返回False。 |
| removeAll(collection) | 此方法用于从集合中删除所有存在于给定集合中的元素。如果由于调用而更改了此集合,则此方法返回true。 |
| retainAll(collection) | 此方法用于仅保留给定集合中提到的集合中的所有元素。如果由于调用而更改了此集合,则此方法返回true。 |
| size() | 此方法用于获取集合的大小。它返回一个整数值,指示元素个数。 |
| toArray() | 此方法用于形成与Set相同元素的数组。 |
| toArray(T[] a) | 返回一个数组,其中包含此集合中的所有元素;返回数组的运行时类型是指定数组的类型。 |
LinkedHashMap和LinkedHashSet之间的区别如下:
| 类别 | LinkedHashMap | LinkedHashSet |
|---|---|---|
| 操作 | 用于存储键值对。 | 用于存储对象集合。 |
| 重复 | 接受唯一的且无重复键,但可接受重复值。 | 不接受重复元素。 |
| 实现 | HashMap | HashSet |
| 实例 | Map<String, Integer> lhm = new LinkedHashMap<String, Integer>(); | Set |
注意: 在LinkedHashmap和LinkedHashset中保持插入排序会增加额外的CPU周期和内存消耗。如果不需要维护插入顺序,建议使用较轻量级的HashSet和HashMap。
极客教程