📜  Java中的集合类

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

Java中的集合类

Collections类是Java Collections Framework 的成员。 Java.util.Collections 包是包含 Collections 类的包。 Collections 类基本上与对集合进行操作或返回集合的静态方法一起使用。如果传递给方法的集合或对象为 null,则此类的所有方法都会抛出NullPointerException

语法:声明

public class Collections
extends Object

集合类字段

集合类基本上包含下面列出的 3 个字段,可用于返回不可变实体。

  • EMPTY_LIST 获取不可变的空列表
  • EMPTY_SET 获取不可变的空 Map
  • EMPTY_MAP 得到一个不可变的空 Set

现在让我们讨论这个类中存在的方法,以便我们稍后可以在我们的程序中实现这些内置功能。下面以表格形式列出了下面的方法,如下所示:

Methods

Description

addAll(Collection c)It is used to insert the specified collection elements in the invoking collection.
asLifoQueue​(Deque deque)This method returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
binarySearch(List list, T key)This method searches the key using binary search in the specified list. 
binarySearch​(List list, T key, Comparator c)This method searches the specified list for the specified object using the binary search algorithm.
checkedCollection​(Collection c, Class type)This method returns a dynamically typesafe view of the specified collection.
checkedList​(List list, Class type)This method returns a dynamically typesafe view of the specified list.
checkedMap​(Map m, Class keyType, Class valueType)This method returns a dynamically typesafe view of the specified map.
checkedNavigableMap​(NavigableMap m, Class keyType, Class valueType)This method returns a dynamically typesafe view of the specified navigable map.
checkedNavigableSet​(NavigableSet s, Class type)This method returns a dynamically typesafe view of the specified navigable set.
checkedQueue​(Queue queue, Class type)This method returns a dynamically typesafe view of the specified queue.
 checkedSet​(Set s, Class type)This method returns a dynamically typesafe view of the specified set.
checkedSortedMap​(SortedMap m, Class keyType, Class valueType)This method returns a dynamically typesafe view of the specified sorted map.
checkedSortedSet​(SortedSet s, Class type)This method returns a dynamically typesafe view of the specified sorted set.
copy​(List dest, List src)This method copies all of the elements from one list into another.
disjoint​(Collection c1, Collection c2)This method returns true if the two specified collections have no elements in common.
emptyEnumeration()This method returns an enumeration that has no elements.
emptyIterator()This method returns an iterator that has no elements.
 emptyList()This method returns an empty list (immutable).
emptyListIterator()This method returns a list iterator that has no elements.
emptyMap()This method returns an empty map (immutable).
emptyNavigableMap()This method returns an empty navigable map (immutable).
emptyNavigableSet()This method returns an empty navigable set (immutable).
emptySet()This method returns an empty set (immutable).
emptySortedMap()This method returns an empty sorted map (immutable).
emptySortedSet()This method returns an empty sorted set (immutable).
enumeration​(Collection c)This method returns an enumeration over the specified collection.
fill​(List list, T obj)This method replaces all of the elements of the specified list with the specified element.
frequency​(Collection c, Object o)This method returns the number of elements in the specified collection equal to the specified object.
indexOfSubList​(List source, List target)This method returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
lastIndexOfSubList​(List source, List target)This method returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
list​(Enumeration e)This method returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
max​(Collection coll)This method returns the maximum element of the given collection, according to the natural ordering of its elements.
max​(Collection coll, Comparator comp)This method returns the maximum element of the given collection, according to the order induced by the specified comparator.
min​(Collection coll)This method returns the minimum element of the given collection, according to the natural ordering of its elements.
min​(Collection coll, Comparator comp)This method returns the minimum element of the given collection, according to the order induced by the specified comparator.
nCopies​(int n, T o)This method returns an immutable list consisting of n copies of the specified object.
newSetFromMap​(Map map)This method returns a set backed by the specified map.
replaceAll​(List list, T oldVal, T newVal)This method replaces all occurrences of one specified value in a list with another.
reverse​(List list)This method reverses the order of the elements in the specified list
reverseOrder()This method returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
 reverseOrder​(Comparator cmp)This method returns a comparator that imposes the reverse ordering of the specified comparator.
rotate​(List list, int distance)This method rotates the elements in the specified list by the specified distance.
shuffle​(List list)This method randomly permutes the specified list using a default source of randomness.
shuffle​(List list, Random rnd)This method randomly permute the specified list using the specified source of randomness.
singletonMap​(K key, V value)This method returns an immutable map, mapping only the specified key to the specified value.
singleton​(T o)This method returns an immutable set containing only the specified object.
singletonList​(T o)This method returns an immutable list containing only the specified object.
sort​(List list)This method sorts the specified list into ascending order, according to the natural ordering of its elements.
sort​(List list, Comparator c)This method sorts the specified list according to the order induced by the specified comparator.
swap​(List list, int i, int j)This method swaps the elements at the specified positions in the specified list.
synchronizedCollection​(Collection c)This method returns a synchronized (thread-safe) collection backed by the specified collection.
synchronizedList​(List list)This method returns a synchronized (thread-safe) list backed by the specified list.
synchronizedMap​(Map m)This method returns a synchronized (thread-safe) map backed by the specified map.
synchronizedNavigableMap​(NavigableMap m)This method returns a synchronized (thread-safe) navigable map backed by the specified navigable map.
synchronizedNavigableSet​(NavigableSet s)This method returns a synchronized (thread-safe) navigable set backed by the specified navigable set.
 synchronizedSet​(Set s)This method returns a synchronized (thread-safe) set backed by the specified set.
synchronizedSortedMap​(SortedMap m)This method returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
synchronizedSortedSet​(SortedSet s)This method returns a synchronized (thread-safe) sorted set backed by the specified sorted set.
unmodifiableCollection​(Collection c)This method returns an unmodifiable view of the specified collection.
unmodifiableList​(List list)This method returns an unmodifiable view of the specified list.
unmodifiableNavigableMap​(NavigableMap m)This method returns an unmodifiable view of the specified navigable map.
unmodifiableNavigableSet​(NavigableSet s)This method returns an unmodifiable view of the specified navigable set.
unmodifiableSet​(Set s)This method returns an unmodifiable view of the specified set.
unmodifiableSortedMap​(SortedMap m)This method returns an unmodifiable view of the specified sorted map.
unmodifiableSortedSet​(SortedSet s)This method returns an unmodifiable view of the specified sorted set.

现在,我们已经完成了列出所有方法的工作,因此当我们考虑全局编程时,我们对这些方法的重要性有了一个微弱的暗示。编写优化代码时重要且经常广泛使用的方法,因为您会在几乎每个Java优化代码中以某种方式看到这些方法,因为Java中 Collections 类的严重使用。因此,这里更有可能在任何课程中,我们不仅会实现该方法,还会讨论可以执行的操作,以便在实现相同的同时具有概念清晰和强大的命令。我们将讨论的操作如下:

  • 向集合中添加元素
  • 排序集合
  • 在集合中搜索
  • 复制元素
  • 不相交的集合

操作一:向Collections类对象添加元素

Java.util.Collections类的 addAll() 方法用于将所有指定元素添加到指定集合中。要添加的元素可以单独指定或作为数组指定。

例子

Java
// Java Program to Demonstrate Adding Elements
// Using addAll() method
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a list
        // Declaring object of string type
        List items = new ArrayList<>();
 
        // Adding elements (items) to the list
        items.add("Shoes");
        items.add("Toys");
 
        // Add one or more elements
        Collections.addAll(items, "Fruits", "Bat", "Ball");
 
        // Printing the list contents
        for (int i = 0; i < items.size(); i++) {
            System.out.print(items.get(i) + " ");
        }
    }
}


Java
// Java program to demonstrate sorting
// a Collections using sort() method
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main Class
// SortingCollectionExample
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a list
        // Declaring object of string type
        List items = new ArrayList<>();
 
        // Adding elements to the list
        // using add() method
        items.add("Shoes");
        items.add("Toys");
 
        // Adding one or more elements using addAll()
        Collections.addAll(items, "Fruits", "Bat", "Mouse");
 
        // Sorting according to default ordering
        // using sort() method
        Collections.sort(items);
 
        // Printing the elements
        for (int i = 0; i < items.size(); i++) {
            System.out.print(items.get(i) + " ");
        }
 
        System.out.println();
 
        // Sorting according to reverse ordering
        Collections.sort(items, Collections.reverseOrder());
 
        // Printing the reverse order
        for (int i = 0; i < items.size(); i++) {
            System.out.print(items.get(i) + " ");
        }
    }
}


Java
// Java Program to Demonstrate Binary Search
// Using Collections.binarySearch()
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
// BinarySearchOnACollection
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a List
        // Declaring object of string type
        List items = new ArrayList<>();
 
        // Adding elements to object
        // using add() method
        items.add("Shoes");
        items.add("Toys");
        items.add("Horse");
        items.add("Ball");
        items.add("Grapes");
 
        // Sort the List
        Collections.sort(items);
 
        // BinarySearch on the List
        System.out.println(
            "The index of Horse is "
            + Collections.binarySearch(items, "Horse"));
 
        // BinarySearch on the List
        System.out.println(
            "The index of Dog is "
            + Collections.binarySearch(items, "Dog"));
    }
}


Java
// Java Program to Demonstrate Copying Elements
// Using copy() method
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
// CopyOneCollectionToAnother
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create destination list
        List destination_List = new ArrayList<>();
 
        // Add elements
        destination_List.add("Shoes");
        destination_List.add("Toys");
        destination_List.add("Horse");
        destination_List.add("Tiger");
 
        // Print the elements
        System.out.println(
            "The Original Destination list is ");
 
        for (int i = 0; i < destination_List.size(); i++) {
            System.out.print(destination_List.get(i) + " ");
        }
        System.out.println();
 
        // Create source list
        List source_List = new ArrayList<>();
 
        // Add elements
        source_List.add("Bat");
        source_List.add("Frog");
        source_List.add("Lion");
 
        // Copy the elements from source to destination
        Collections.copy(destination_List, source_List);
 
        // Printing the modified list
        System.out.println(
            "The Destination List After copying is ");
 
        for (int i = 0; i < destination_List.size(); i++) {
            System.out.print(destination_List.get(i) + " ");
        }
    }
}


Java
// Java Program to Illustrate Working of Disjoint Function
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
// DisjointCollectionsExample
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create list1
        List list1 = new ArrayList<>();
 
        // Add elements to list1
        list1.add("Shoes");
        list1.add("Toys");
        list1.add("Horse");
        list1.add("Tiger");
 
        // Create list2
        List list2 = new ArrayList<>();
 
        // Add elements to list2
        list2.add("Bat");
        list2.add("Frog");
        list2.add("Lion");
 
        // Check if disjoint or not
        System.out.println(
            Collections.disjoint(list1, list2));
    }
}


输出
Shoes Toys Fruits Bat Ball 

操作2:对集合进行排序

Java.util.Collections.sort() 用于按升序对指定的 Collection 列表中存在的元素进行排序。 Java.util.Collections.reverseOrder() 用于按降序排序。

例子

Java

// Java program to demonstrate sorting
// a Collections using sort() method
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main Class
// SortingCollectionExample
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a list
        // Declaring object of string type
        List items = new ArrayList<>();
 
        // Adding elements to the list
        // using add() method
        items.add("Shoes");
        items.add("Toys");
 
        // Adding one or more elements using addAll()
        Collections.addAll(items, "Fruits", "Bat", "Mouse");
 
        // Sorting according to default ordering
        // using sort() method
        Collections.sort(items);
 
        // Printing the elements
        for (int i = 0; i < items.size(); i++) {
            System.out.print(items.get(i) + " ");
        }
 
        System.out.println();
 
        // Sorting according to reverse ordering
        Collections.sort(items, Collections.reverseOrder());
 
        // Printing the reverse order
        for (int i = 0; i < items.size(); i++) {
            System.out.print(items.get(i) + " ");
        }
    }
}
输出
Bat Fruits Mouse Shoes Toys 
Toys Shoes Mouse Fruits Bat 

操作 3:在集合中搜索

Java.util.Collections.binarySearch() 方法返回对象在排序列表中的位置。使用此方法时,列表应按升序排列,否则该方法返回的结果将是错误的。如果该元素存在于列表中,则该方法将返回该元素在排序列表中的位置,否则,该方法返回的结果将是–(如果存在该元素应该存在的插入点)-1) .

例子

Java

// Java Program to Demonstrate Binary Search
// Using Collections.binarySearch()
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
// BinarySearchOnACollection
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a List
        // Declaring object of string type
        List items = new ArrayList<>();
 
        // Adding elements to object
        // using add() method
        items.add("Shoes");
        items.add("Toys");
        items.add("Horse");
        items.add("Ball");
        items.add("Grapes");
 
        // Sort the List
        Collections.sort(items);
 
        // BinarySearch on the List
        System.out.println(
            "The index of Horse is "
            + Collections.binarySearch(items, "Horse"));
 
        // BinarySearch on the List
        System.out.println(
            "The index of Dog is "
            + Collections.binarySearch(items, "Dog"));
    }
}
输出
The index of Horse is 2
The index of Dog is -2

操作 4:复制元素

Java.util.Collections类的 copy() 方法用于将一个列表中的所有元素复制到另一个列表中。操作后,目标列表中每个复制元素的索引将与其在源列表中的索引相同。目标列表必须至少与源列表一样长。如果它更长,则目标列表中的其余元素不受影响。

例子

Java

// Java Program to Demonstrate Copying Elements
// Using copy() method
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
// CopyOneCollectionToAnother
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create destination list
        List destination_List = new ArrayList<>();
 
        // Add elements
        destination_List.add("Shoes");
        destination_List.add("Toys");
        destination_List.add("Horse");
        destination_List.add("Tiger");
 
        // Print the elements
        System.out.println(
            "The Original Destination list is ");
 
        for (int i = 0; i < destination_List.size(); i++) {
            System.out.print(destination_List.get(i) + " ");
        }
        System.out.println();
 
        // Create source list
        List source_List = new ArrayList<>();
 
        // Add elements
        source_List.add("Bat");
        source_List.add("Frog");
        source_List.add("Lion");
 
        // Copy the elements from source to destination
        Collections.copy(destination_List, source_List);
 
        // Printing the modified list
        System.out.println(
            "The Destination List After copying is ");
 
        for (int i = 0; i < destination_List.size(); i++) {
            System.out.print(destination_List.get(i) + " ");
        }
    }
}
输出
The Original Destination list is 
Shoes Toys Horse Tiger 
The Destination List After copying is 
Bat Frog Lion Tiger 

操作 5:不相交收集

Java.util.Collections.disjoint() 用于检查两个指定的集合是否不相交。更正式地说,如果两个集合没有共同的元素,则它们是不相交的。如果两个集合没有任何共同元素,则返回 true。

例子

Java

// Java Program to Illustrate Working of Disjoint Function
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
// DisjointCollectionsExample
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create list1
        List list1 = new ArrayList<>();
 
        // Add elements to list1
        list1.add("Shoes");
        list1.add("Toys");
        list1.add("Horse");
        list1.add("Tiger");
 
        // Create list2
        List list2 = new ArrayList<>();
 
        // Add elements to list2
        list2.add("Bat");
        list2.add("Frog");
        list2.add("Lion");
 
        // Check if disjoint or not
        System.out.println(
            Collections.disjoint(list1, list2));
    }
}
输出
true