Java中的集合接口及其示例
Collection 界面是Java集合框架的成员之一,它是java.util包的一部分。它是Collection层次结构的根接口之一。Collection接口不会被任何类直接实现。但是,它间接地通过其子类型或子接口(如List、Queue和Set)进行实现。
例如,《HashSet》类实现了Set接口,该接口是Collection接口的一个子接口。如果集合实现不实现特定的操作,则它应定义相应的方法来抛出 UnsupportedOperationException 异常。
Collection继承体系

它实现了 Iterable
Collection接口的子接口
所有Collection框架的类都实现了Collection接口的子接口。Collection接口的所有方法也包含在它的子接口中。这些子接口有时被称为 Collection类型 或 Collection的子类型 。包括以下内容:
List : 这是集合接口的子接口。此接口专用于列表类型的数据,其中我们可以存储所有对象的有序集合。 这也允许重复的数据存在。此List接口由各种类实现,如ArrayList、Vector、Stack等。由于所有子类都实现了列表,因此我们可以使用任何这些类之一实例化一个列表对象。例如,
List <T> al = new ArrayList<> ();
List <T> ll = new LinkedList<> ();
List <T> v = new Vector<> ();
其中T是对象的类型。
Set : 集合是一个无序集合,在其中不能存储重复值。当我们希望避免对象的重复并希望仅存储唯一对象时使用此集合。此set接口由各种类实现,如HashSet、TreeSet、LinkedHashSet等。由于所有的子类都实现了set,因此我们可以使用任何这些类之一实例化一个set对象。例如,
Set<T> hs = new HashSet<> ();
Set<T> lhs = new LinkedHashSet<> ();
Set<T> ts = new TreeSet<> ();
其中T是对象的类型。
SortedSet : 此接口与set接口非常相似。唯一的区别是该接口具有维护元素排序的额外方法。Sorted Set接口扩展了set接口,并用于处理需要排序的数据。实现此接口的类是TreeSet。由于此类实现了SortedSet,因此我们可以使用此类实例化SortedSet对象。例如,
SortedSet<T> ts = new TreeSet<> ();
其中T是对象的类型。
队列 :正如其名称所示,队列接口维护类似于现实世界队列线的FIFO(先进先出)顺序。此接口专用于存储顺序关系很重要的所有元素。例如,每当我们尝试预订机票时,票是按照先到先得的原则出售的。因此,首先进入队列的人得到票。有各种类,如PriorityQueue,Deque,ArrayDeque等。由于所有这些子类都实现了队列,因此我们可以使用这些类中的任何一个来实例化队列对象。例如,
Queue <T> pq = new PriorityQueue<> ();
Queue <T> ad = new ArrayDeque<> ();
其中T是对象的类型。
Deque :这是队列数据结构的一个非常微小的变化。Deque,也称为双端队列,是一种数据结构,我们可以从队列的两端添加和删除元素。该接口扩展了队列接口。实现此接口的类是ArrayDeque。由于这个类实现了deque,因此我们可以使用此类来实例化deque对象。例如,
Deque<T> ad = new ArrayDeque<> ();
其中T是对象的类型。
声明:
public interface Collection<E> extends Iterable<E>
这里, E 是存储在集合中的元素类型。
示例:
// Java program to illustrate Collection interface
import java.io.*;
import java.util.*;
public class CollectionDemo {
public static void main(String args[])
{
// creating an empty LinkedList
Collection<String> list = new LinkedList<String>();
// use add() method to add elements in the list
list.add("Geeks");
list.add("for");
list.add("Geeks");
// Output the present list
System.out.println("The list is: " + list);
// Adding new elements to the end
list.add("Last");
list.add("Element");
// printing the new list
System.out.println("The new List is: " + list);
}
}
输出
The list is: [Geeks, for, Geeks]
The new List is: [Geeks, for, Geeks, Last, Element]
实现的类
AbstractCollection、AbstractList、AbstractQueue、AbstractSequentialList、AbstractSet、ArrayBlockingQueue、ArrayDeque、ArrayList、AttributeList、BeanContextServicesSupport、BeanContextSupport、ConcurrentHashMap.KeySetView、ConcurrentLinkedDeque、ConcurrentLinkedQueue、ConcurrentSkipListSet、CopyOnWriteArrayList、CopyOnWriteArraySet、DelayQueue、EnumSet、HashSet、JobStateReasons、LinkedBlockingDeque、LinkedBlockingQueue、LinkedHashSet、LinkedList、LinkedTransferQueue、PriorityBlockingQueue、PriorityQueue、RoleList、RoleUnresolvedList、 Stack、SynchronousQueue、TreeSet、Vector都实现了Collection接口。
语法:
Collection<E> objectName = new ArrayList<E>();
这里, E 是存储在集合中的元素类型。
注意: 在上面的语法中,如果该类实现了Collection接口,则可以用ArrayList替换任何类。
基本操作
1.添加元素
通过 Collection 提供的 add(E e) 和 addAll(Collection c) 方法可以添加元素。
// Java 代码演示
// 向 Collection 添加元素
import java.io.*;
import java.util.*;
public class AddingElementsExample {
public static void main(String[] args)
{
// 创建一个具有初始容量的空 ArrayList
Collection<Integer> list1 = new ArrayList<Integer>(5);
// 使用 add() 方法向列表中添加元素
list1.add(15);
list1.add(20);
list1.add(25);
// 打印列表中所有可用的元素
for (Integer number : list1) {
System.out.println("Number = " + number);
}
// 创建一个空的 ArrayList
Collection<Integer> list2 = new ArrayList<Integer>();
// 将集合追加到列表中
list2.addAll(list1);
// 显示修改后的 ArrayList
System.out.println("The new ArrayList is: " + list2);
}
}
输出结果
Number = 15
Number = 20
Number = 25
The new ArrayList is: [15, 20, 25]
2. 删除元素
remove(E e) 和 removeAll(Collection c) 方法可以用于从集合中删除特定元素或一组元素。
// Java 程序演示如何从集合中删除元素
import java.util.*;
public class RemoveElementsExample {
public static void main(String[] argv) throws Exception
{
// 创建一个 HashSet<Integer> 对象
Collection<Integer> set1 = new HashSet<Integer>();
// 向 set1 中添加元素
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(4);
set1.add(5);
// 打印 set1
System.out.println("Initial set1 : " + set1);
// 删除一个特定的元素
set1.remove(4);
// 打印修改后的 set1
System.out.println("set1 after removing 4 : " + set1);
// 创建另一个 HashSet<Integer> 对象
Collection<Integer> set2 = new HashSet<Integer>();
set2.add(1);
set2.add(2);
set2.add(3);
// 打印 set2
System.out.println("Collection Elements to be removed : " + set2);
// 使用 removeAll() 方法从 set1 中删除在 set2 中指定的元素
set1.removeAll(set2);
// 打印 set1
System.out.println("set 1 after removeAll() operation : " + set1);
}
}
输出结果
Initial set1 : [1, 2, 3, 4, 5]
set1 after removing 4 : [1, 2, 3, 5]
Collection Elements to be removed : [1, 2, 3]
set 1 after removeAll() operation : [5]
3. 迭代
使用 iterator() 方法迭代 Collection 的元素。
// Java代码展示如何迭代遍历集合
import java.util.*;
public class IteratingExample {
public static void main(String[] args)
{
// 创建并填充列表
Collection<String> list = new LinkedList<>();
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("is");
list.add("a");
list.add("CS");
list.add("Students");
list.add("Portal");
// 显示列表
System.out.println("The list is: " + list);
// 使用iterator()方法为列表创建迭代器
Iterator<String> iter = list.iterator();
// 迭代遍历列表中的值
System.out.println("\nThe iterator values" + " of list are: ");
while (iter.hasNext()) {
System.out.print(iter.next() + " ");
}
}
}
输出
The list is: [Geeks, for, Geeks, is, a, CS, Students, Portal]
The iterator values of list are:
Geeks for Geeks is a CS Students Portal
集合的方法
| 方法 | 描述 |
|---|---|
| add(E e) | 确保此集合包含指定的元素(可选操作)。 |
| addAll(Collection extends E> c) | 将指定集合中的所有元素添加到此集合中(可选操作)。 clear() | 从此集合中移除所有元素(可选操作)。 contains(Object o) | 如果此集合包含指定的元素,则返回 true。 containsAll(Collection> c) |
如果此集合包含指定集合中的所有元素,则返回 true。 |
| equals(Object o) | 将指定对象与此集合进行比较以测试其相等性。 |
| hashCode() | 返回此集合的哈希码值。 |
| isEmpty() | 如果此集合不包含元素,则返回 true。 |
| iterator() | 返回在此集合中的元素上进行迭代的迭代器。 |
| parallelStream() | 返回一个可能并行的流,其源为此集合。 |
| remove(Object o) | 如果存在,则从此集合中移除指定元素的单个实例(可选操作)。 |
| removeAll(Collection> c) | 移除与指定集合中包含相同元素的所有此集合中的元素(可选操作)。 removeIf(Predicate super E> filter) | 移除此集合中满足给定谓词的所有元素。 retainAll(Collection> c) |
仅保留此集合中包含在指定集合中的元素(可选操作)。 |
| size() | 返回此集合中元素的数量。 |
| spliterator() | 创建此集合中元素的 Spliterator。 |
| stream() | 返回一个序列流,其源为此集合。 |
| toArray() | 返回一个包含此集合中所有元素的数组。 |
| toArray(IntFunction<T[]> generator) | 使用提供的生成器函数来分配返回的数组,返回一个包含此集合中所有元素的数组。 |
| toArray(T[] a) | 返回一个包含此集合中所有元素的数组;返回数组的运行时类型为指定数组的类型。 |
java.lang.Iterable 接口中声明的方法
| 方法 | 描述 |
|---|---|
| forEach(Consumer<? super T> action) | 对 Iterable 的每个元素执行给定操作,直到所有元素已处理或该操作抛出异常。 |
参考文献: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html
极客教程