📜  Java中的集合接口与示例

📅  最后修改于: 2022-05-13 01:55:16.450000             🧑  作者: Mango

Java中的集合接口与示例

Collection接口是Java Collections Framework 的一个成员。它是Java.util包的一部分。它是集合层次结构的根接口之一。 Collection 接口不是由任何类直接实现的。但是,它是通过其子类型或子接口(如 List、Queue 和 Set)间接实现的。

例如, HashSet 类实现了 Set 接口,它是 Collection 接口的子接口。如果集合实现没有实现特定的操作,它应该定义相应的方法来抛出UnsupportedOperationException

收藏的层次结构

带有示例的 Java 中的集合接口

它实现了Iterable接口。 Collection 的子接口有BeanContext , BeanContextServices , BlockingDeque, BlockingQueue, Deque, EventSet , List, NavigableSet, Queue, Set, SortedSet< E>, TransferQueue

集合接口的子接口

集合框架的所有类都实现了集合接口的子接口。 Collection 接口的所有方法也包含在它的子接口中。这些子接口有时被称为集合类型或集合的子类型。这些包括以下内容:

List :这是集合接口的子接口。该接口专用于列表类型的数据,我们可以在其中存储对象的所有有序集合。这也允许其中存在重复数据。这个列表接口由各种类实现,如 ArrayList、Vector、Stack 等。由于所有子类都实现了列表,我们可以使用这些类中的任何一个实例化列表对象。例如,

集合:集合是无法存储重复值的无序对象集合。当我们希望避免对象重复并希望仅存储唯一对象时,将使用此集合。这个集合接口由各种类实现,如 HashSet、TreeSet、LinkedHashSet 等。由于所有子类都实现了集合,我们可以用这些类中的任何一个实例化一个集合对象。例如,

SortedSet :这个接口与 set 接口非常相似。唯一的区别是这个接口有额外的方法来维护元素的顺序。 sorted set接口扩展了set接口,用于处理需要排序的数据。实现这个接口的类是TreeSet。由于这个类实现了 SortedSet,我们可以用这个类实例化一个 SortedSet 对象。例如,

队列:顾名思义,队列接口维护 FIFO(先进先出)顺序,类似于现实世界的队列行。此接口专用于存储元素顺序重要的所有元素。例如,每当我们尝试订票时,门票都是按照先到先得的原则出售的。因此,请求首先到达队列的人获得票。有各种类,如 PriorityQueue、Deque、ArrayDeque 等。由于所有这些子类都实现了队列,我们可以使用这些类中的任何一个来实例化队列对象。例如,

Deque :这是队列数据结构的一个非常小的变化。 Deque,也称为双端队列,是一种数据结构,我们可以在其中添加和删除队列两端的元素。该接口扩展了队列接口。实现这个接口的类是ArrayDeque。由于这个类实现了双端队列,我们可以用这个类实例化一个双端队列对象。例如,

宣言:

public interface Collection extends Iterable

这里, E是存储在集合中的元素类型。

例子:

Java
// 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 list = new LinkedList();
 
        // 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);
    }
}


Java
// Java code to illustrate adding
// elements to the Collection
 
import java.io.*;
import java.util.*;
 
public class AddingElementsExample {
    public static void main(String[] args)
    {
 
        // create an empty array list with an initial
        // capacity
        Collection list1 = new ArrayList(5);
 
        // use add() method to add elements in the list
        list1.add(15);
        list1.add(20);
        list1.add(25);
 
        // prints all the elements available in list
        for (Integer number : list1) {
            System.out.println("Number = " + number);
        }
 
        // Creating an empty ArrayList
        Collection list2 = new ArrayList();
 
        // Appending the collection to the list
        list2.addAll(list1);
 
        // displaying the modified ArrayList
        System.out.println("The new ArrayList is: " + list2);
    }
}


Java
// Java program to demonstrate removing
// elements from a Collection
 
import java.util.*;
 
public class RemoveElementsExample {
    public static void main(String[] argv) throws Exception
    {
 
        // Creating object of HashSet
        Collection set1 = new HashSet();
 
        // Populating arrset1
        set1.add(1);
        set1.add(2);
        set1.add(3);
        set1.add(4);
        set1.add(5);
 
        // print set1
        System.out.println("Initial set1 : " + set1);
         
          // remove a particular element
          set1.remove(4);
       
          // print modified set1
        System.out.println("set1 after removing 4 : " + set1);
       
        // Creating another object of HashSet
        Collection set2 = new HashSet();
        set2.add(1);
        set2.add(2);
        set2.add(3);
 
        // print set2
        System.out.println("Collection Elements to be removed : " + set2);
 
        // Removing elements from set1
        // specified in set2
        // using removeAll() method
        set1.removeAll(set2);
 
        // print arrset1
        System.out.println("set 1 after removeAll() operation : " + set1);
    }
}


Java
// Java code to illustrate iterating
// over a Collection
 
import java.util.*;
 
public class IteratingExample {
 
    public static void main(String[] args)
    {
        // Create and populate the list
        Collection 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");
 
        // Displaying the list
        System.out.println("The list is: " + list);
 
        // Create an iterator for the list
        // using iterator() method
        Iterator iter = list.iterator();
 
        // Displaying the values after iterating
        // through the list
        System.out.println("\nThe iterator values" + " of list are: ");
        while (iter.hasNext()) {
            System.out.print(iter.next() + " ");
        }
    }
}


输出
The list is: [Geeks, for, Geeks]
The new List is: [Geeks, for, Geeks, Last, Element]

实现类

Collection 接口由 AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList , BeanContextServicesSupport , BeanContextSupport , ConcurrentHashMap.KeySetView, ConcurrentLinkedDeque, ConcurrentLinkedSetQueue, ConcurrentSkipListSet, CopyOnWriteHashArrays, DequeOnWriteHashons, DeleOnWriteHash , LinkedBlockingDeque、LinkedBlockingQueue、LinkedHashSet、LinkedList、LinkedTransferQueue、PriorityBlockingQueue、PriorityQueue、 RoleListRoleUnresolvedList 、Stack、 SynchronousQueue 、TreeSet、Vector。

句法:

Collection objectName = new ArrayList();

这里, E是存储在集合中的元素类型。

注意:在上面的语法中,如果该类实现了 Collection 接口,我们可以用 ArrayList 替换任何类。

基本操作

1. 添加元素

Collection 提供的 add(E e) 和 addAll(Collection c) 方法可用于添加元素。

Java

// Java code to illustrate adding
// elements to the Collection
 
import java.io.*;
import java.util.*;
 
public class AddingElementsExample {
    public static void main(String[] args)
    {
 
        // create an empty array list with an initial
        // capacity
        Collection list1 = new ArrayList(5);
 
        // use add() method to add elements in the list
        list1.add(15);
        list1.add(20);
        list1.add(25);
 
        // prints all the elements available in list
        for (Integer number : list1) {
            System.out.println("Number = " + number);
        }
 
        // Creating an empty ArrayList
        Collection list2 = new ArrayList();
 
        // Appending the collection to the list
        list2.addAll(list1);
 
        // displaying the modified 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

// Java program to demonstrate removing
// elements from a Collection
 
import java.util.*;
 
public class RemoveElementsExample {
    public static void main(String[] argv) throws Exception
    {
 
        // Creating object of HashSet
        Collection set1 = new HashSet();
 
        // Populating arrset1
        set1.add(1);
        set1.add(2);
        set1.add(3);
        set1.add(4);
        set1.add(5);
 
        // print set1
        System.out.println("Initial set1 : " + set1);
         
          // remove a particular element
          set1.remove(4);
       
          // print modified set1
        System.out.println("set1 after removing 4 : " + set1);
       
        // Creating another object of HashSet
        Collection set2 = new HashSet();
        set2.add(1);
        set2.add(2);
        set2.add(3);
 
        // print set2
        System.out.println("Collection Elements to be removed : " + set2);
 
        // Removing elements from set1
        // specified in set2
        // using removeAll() method
        set1.removeAll(set2);
 
        // print arrset1
        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. 迭代

要迭代 Collection 的元素,我们可以使用iterator()方法。

Java

// Java code to illustrate iterating
// over a Collection
 
import java.util.*;
 
public class IteratingExample {
 
    public static void main(String[] args)
    {
        // Create and populate the list
        Collection 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");
 
        // Displaying the list
        System.out.println("The list is: " + list);
 
        // Create an iterator for the list
        // using iterator() method
        Iterator iter = list.iterator();
 
        // Displaying the values after iterating
        // through the list
        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

收集方法

METHOD

DESCRIPTION

add​(E e)Ensures that this collection contains the specified element (optional operation).
addAll​(Collection c)Adds all the elements in the specified collection to this collection (optional operation).
clear()Removes all the elements from this collection (optional operation).
contains​(Object o)Returns true if this collection contains the specified element.
containsAll​(Collection c)Returns true if this collection contains all the elements in the specified collection.
equals​(Object o)Compares the specified object with this collection for equality.
hashCode()Returns the hash code value for this collection.
isEmpty()Returns true if this collection contains no elements.
iterator()Returns an iterator over the elements in this collection.
parallelStream()Returns a possibly parallel Stream with this collection as its source.
remove​(Object o)Removes a single instance of the specified element from this collection, if it is present (optional operation).
removeAll​(Collection c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
removeIf​(Predicate filter)Removes all the elements of this collection that satisfy the given predicate.
retainAll​(Collection c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
size()Returns the number of elements in this collection.
spliterator()Creates a Spliterator over the elements in this collection.
stream()Returns a sequential Stream with this collection as its source.
toArray()Returns an array containing all the elements in this collection.
toArray​(IntFunction generator)Returns an array containing all the elements in this collection, using the provided generator function to allocate the returned array.
toArray​(T[] a)Returns an array containing all the elements in this collection; the runtime type of the returned array is that of the specified array.

在接口Java .lang.Iterable 中声明的方法

METHOD

DESCRIPTION

forEach​(Consumer action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

参考: Java : Java