java集合替换集合

Java Collections Framework is one of the core parts of the Java programming language. Collections are used in almost every programming language. Most of the programming languages support various type of collections such as List, Set, Queue, Stack, etc.

Java Collections Framework是Java编程语言的核心部分之一。 集合几乎用于每种编程语言中。 大多数编程语言都支持各种类型的集合,例如列表,集合,队列,堆栈等。

Java中的集合 (Collections in Java)

  1. What is Java Collections Framework?什么是Java Collections Framework?
  2. Benefits of Java Collections FrameworkJava Collections Framework的好处
  3. Java Collections Interfaces
    1. Collection Interface
    2. Iterator Interface
    3. Set Interface
    4. List Interface
    5. Queue Interface
    6. Dequeue Interface
    7. Map Interface
    8. ListIterator Interface
    9. SortedSet Interface
    10. SortedMap Interface

    Java Collections接口

    1. 采集界面
    2. 迭代器接口
    3. 设置界面
    4. 列表界面
    5. 队列接口
    6. 出队接口
    7. 地图界面
    8. ListIterator接口
    9. SortedSet接口
    10. SortedMap接口
  4. Java Collections Classes
    1. HashSet Class
    2. TreeSet Class
    3. ArrayList Class
    4. LinkedList Class
    5. HashMap Class
    6. TreeMap Class
    7. PriorityQueue Class

    Java Collections类

    1. HashSet类别
    2. TreeSet类
    3. ArrayList类
    4. LinkedList类
    5. HashMap类别
    6. TreeMap类
    7. PriorityQueue类
  5. Collections class收藏类
  6. Synchronized Wrappers同步包装
  7. Unmodifiable wrappers不可修改的包装器
  8. Thread Safe Collections线程安全集合
  9. Collections API Algorithms
    1. Sorting
    2. Shuffling
    3. Searching
    4. Composition
    5. Min and Max values

    集合API算法

    1. 排序
    2. 改组
    3. 正在搜寻
    4. 组成
    5. 最小值和最大值
  10. Java 8 Collections API FeaturesJava 8 Collections API功能
  11. Java 10 Collections API ChangesJava 10 Collections API的更改
  12. Java 11 Collections API ChangesJava 11 Collections API的更改
  13. Collection classes in a Nutshell简而言之集合类

1.什么是Java Collections Framework? (1. What is Java Collections Framework?)

Collections are like containers that group multiple items in a single unit. For example, a jar of chocolates, list of names, etc.

集合就像容器一样,将多个项目组合在一个单元中。 例如,一罐巧克力,名称列表等。

Collections are used in every programming language and when Java arrived, it also came with few Collection classes – Vector, Stack, Hashtable, Array.

每种编程语言都使用Collections,而Java到来时,它也带有一些Collection类-VectorStackHashtableArray

Java 1.2 provided Collections Framework that is the architecture to represent and manipulate Collections in java in a standard way. Java Collections Framework consists of the following parts:

Java 1.2提供了Collections Framework ,这是一种以标准方式表示和操纵Java中Collections的体系结构。 Java Collections Framework由以下部分组成:

  • Interfaces: Java Collections Framework interfaces provides the abstract data type to represent collection. java.util.Collection is the root interface of Collections Framework. It is on the top of Collections framework hierarchy. It contains some important methods such as size(), iterator(), add(), remove(), clear() that every Collection class must implement.

    Some other important interfaces are java.util.List, java.util.Set, java.util.Queue and java.util.Map.

    The Map is the only interface that doesn’t inherit from Collection interface but it’s part of the Collections framework. All the collections framework interfaces are present in java.util package.

    接口 :Java Collections Framework接口提供抽象数据类型来表示集合。 java.util.Collection是Collections Framework的根接口。 它在Collections框架层次结构的顶部。 它包含每个Collection类必须实现的一些重要方法,例如size()iterator()add()remove()clear()

    其他一些重要的接口是java.util.Listjava.util.Setjava.util.Queuejava.util.Map

    Map是唯一一个不从Collection接口继承的接口,但它是Collections框架的一部分。 所有collections框架接口都存在于java.util包中。

  • Implementation Classes: Java Collections framework provides core implementation classes for collections. We can use them to create different types of collections in java program.

    Some important collection classes are ArrayList, LinkedList, HashMap, TreeMap, HashSet, TreeSet.

    These classes solve most of our programming needs but if we need some special collection class, we can extend them to create our custom collection class.

    Java 1.5 came up with thread-safe collection classes that allowed to modify Collections while iterating over it. Some of them are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

    These classes are in java.util.concurrent package. All the collection classes are present in java.util and java.util.concurrent package.

    实现类 :Java Collections框架提供了集合的核心实现类。 我们可以使用它们在java程序中创建不同类型的集合。

    一些重要的集合类是ArrayListLinkedListHashMapTreeMapHashSetTreeSet

    这些类解决了我们大多数的编程需求,但是如果我们需要一些特殊的集合类,我们可以扩展它们以创建我们的自定义集合类。

    Java 1.5提供了线程安全的集合类,该类允许在迭代它的同时修改Collections。 其中一些是CopyOnWriteArrayListConcurrentHashMapCopyOnWriteArraySet

    这些类位于java.util.concurrent包中。 所有集合类都存在于java.utiljava.util.concurrent包中。

  • Algorithms: Algorithms are useful methods to provide some common functionalities, for example searching, sorting and shuffling.算法 :算法是提供一些常用功能的有用方法,例如搜索,排序和改组。

Below class diagram shows Collections Framework hierarchy. For simplicity, I have included only commonly used interfaces and classes.

下面的类图显示了Collections Framework层次结构。 为简单起见,我仅包括常用的接口和类。

2. Java Collections Framework的好处 (2. Benefits of Java Collections Framework)

Java Collections framework have following benefits:

Java Collections框架具有以下优点:

  • Reduced Development Effort – It comes with almost all common types of collections and useful methods to iterate and manipulate the data. So we can concentrate more on business logic rather than designing our collection APIs.减少的开发工作量 –几乎所有常见类型的集合都带有它,并提供有用的方法来迭代和处理数据。 因此,我们可以将更多精力放在业务逻辑上,而不是设计我们的集合API。
  • Increased Quality – Using core collection classes that are well tested increases our program quality rather than using any home developed data structure.提高质量 –使用经过良好测试的核心集合类可以提高我们的程序质量,而不是使用任何自行开发的数据结构。
  • Reusability and Interoperability可重用性和互操作性
  • Reduce effort – to learn any new API if we use core collection API classes.减少工作量 –如果我们使用核心集合API类,则可以学习任何新的API。

3. Java Collections接口 (3. Java Collections Interfaces)

Java collection interfaces are the foundation of the Java Collections Framework. Note that all the core collection interfaces are generic; for example public interface Collection<E>. The <E> syntax is for Generics and when we declare Collection, we should use it to specify the type of Object it can contain. It helps in reducing run-time errors by type-checking the Objects at compile-time.

Java集合接口是Java集合框架的基础。 请注意,所有核心集合接口都是通用的。 例如public interface Collection<E> 。 <E>语法适用于泛型 ,当我们声明Collection时,应该使用它来指定它可以包含的Object的类型。 通过在编译时对对象进行类型检查,它有助于减少运行时错误。

To keep the number of core collection interfaces manageable, the Java platform doesn’t provide separate interfaces for each variant of each collection type. If an unsupported operation is invoked, a collection implementation throws an UnsupportedOperationException.

为了使核心集合接口的数量易于管理,Java平台没有为每种集合类型的每个变体提供单独的接口。 如果调用了不受支持的操作,则收集实现将引发UnsupportedOperationException

3.1)采集接口 (3.1) Collection Interface)

This is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.

这是集合层次结构的根。 集合表示一组称为其元素的对象。 Java平台不提供此接口的任何直接实现。

The interface has methods to tell you how many elements are in the collection (size, isEmpty), to check whether a given object is in the collection (contains), to add and remove an element from the collection (add, remove), and to provide an iterator over the collection (iterator).

该接口具有一些方法来告诉您集合中有多少个元素( sizeisEmpty ),检查给定对象是否在集合中( contains ),从集合中添加和删除元素( addremove )以及在集合上提供迭代器( iterator )。

Collection interface also provides bulk operations methods that work on entire collection – containsAll, addAll, removeAll, retainAll, clear.

Collection接口还提供批量操作方法,关于整个征集工作- containsAlladdAllremoveAllretainAllclear

The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input.

toArray方法是作为集合与期望输入上有数组的旧API之间的桥梁而提供的。

3.2)迭代器接口 (3.2) Iterator Interface)

Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Iterators in collection classes implement Iterator Design Pattern.

迭代器接口提供了对任何Collection进行迭代的方法。 我们可以使用iterator方法从Collection中获取迭代器实例。 在Java Collections Framework中,迭代器代替了Enumeration 。 迭代器允许调用者在迭代过程中从基础集合中删除元素。 集合类中的迭代器实现“ 迭代器设计模式”

3.3)设置界面 (3.3) Set Interface)

Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.

Set是一个不能包含重复元素的集合。 此接口对数学集合的抽象进行建模,并用于表示集合,例如纸牌组。

The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet. Set interface doesn’t allow random-access to an element in the Collection. You can use iterator or foreach loop to traverse the elements of a Set.

Java平台包含三个通用的Set实现: HashSetTreeSetLinkedHashSet 。 Set接口不允许随机访问Collection中的元素。 您可以使用迭代器或foreach循环遍历Set的元素。

3.4)列表界面 (3.4) List Interface)

List is an ordered collection and can contain duplicate elements. You can access any element from its index. List is more like array with dynamic length. List is one of the most used Collection type. ArrayList and LinkedList are implementation classes of List interface.

List是一个有序的集合,可以包含重复的元素。 您可以从其索引访问任何元素。 列表更像是具有动态长度的数组。 列表是最常用的集合类型之一。 ArrayListLinkedList是List接口的实现类。

List interface provides useful methods to add an element at a specific index, remove/replace element based on the index and to get a sub-list using the index.

列表接口提供了有用的方法,可以在特定索引处添加元素,基于索引移除/替换元素以及使用索引获取子列表。

List strList = new ArrayList<>();//add at last
strList.add(0, "0");//add at specified index
strList.add(1, "1");//replace
strList.set(1, "2");//remove
strList.remove("1");

Collections class provide some useful algorithm for List – sort, shuffle, reverse, binarySearch etc.

集合类列表提供一些有用的算法- sortshufflereversebinarySearch等。

3.5)队列接口 (3.5) Queue Interface)

Queue is a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.

队列是用于在处理之前保存多个元素的集合。 除了基本的收集操作外,队列还提供其他插入,提取和检查操作。

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements’ natural ordering. Whatever the ordering used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue.

队列通常但不一定以FIFO(先进先出)的方式对元素进行排序。 优先队列除外,它们根据提供的比较器或元素的自然顺序对元素进行排序。 无论使用哪种顺序,队列的开头都是将通过调用remove或poll删除的元素。 在FIFO队列中,所有新元素都插入队列的尾部。

3.6)出队接口 (3.6) Dequeue Interface)

A linear collection that supports element insertion and removal at both ends. The name deque is short for “double-ended queue” and is usually pronounced “deck”. Most Deque implementations place no fixed limits on the number of elements they may contain, but this interface supports capacity-restricted deques as well as those with no fixed size limit.

支持在两端插入和删除元素的线性集合。 deque这个名字是“双端队列”的缩写,通常发音为“ deck”。 大多数Deque实施对它们可能包含的元素数量没有固定的限制,但是此接口支持容量受限的双端队列以及没有固定大小限制的双端队列。

This interface defines methods to access the elements at both ends of the deque. Methods are provided to insert, remove, and examine the element.

此接口定义访问双端队列两端的元素的方法。 提供了用于插入,删除和检查元素的方法。

3.7)地图界面 (3.7) Map Interface)

Java Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

Java Map是一个将键映射到值的对象。 映射不能包含重复的键:每个键最多可以映射到一个值。

The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap.

Java平台包含三个通用Map实现: HashMapTreeMapLinkedHashMap

The basic operations of Map are put, get, containsKey, containsValue, size, and isEmpty.

Map的基本操作包括putgetcontainsKeycontainsValuesizeisEmpty

3.8)ListIterator接口 (3.8) ListIterator Interface)

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list.

列表的迭代器,允许程序员沿任一方向遍历列表,在迭代过程中修改列表,并获取迭代器在列表中的当前位置。

Java ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

Java ListIterator没有当前元素; 它的光标位置始终位于通过调用previous()返回的元素和通过调用next()返回的元素之间。

3.9)SortedSet接口 (3.9) SortedSet Interface)

SortedSet is a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.

SortedSet是一个Set,它按升序维护其元素。 提供了一些附加的操作以利用订购的优势。 排序的集合用于自然排序的集合,例如单词列表和成员身份记录。

3.10)SortedMap接口 (3.10) SortedMap Interface)

Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.

以升序顺序维护其映射的Map。 这是SortedSet的Map类似物。 排序后的地图用于键/值对的自然排序集合,例如字典和电话簿。

4. Java集合类 (4. Java Collections Classes)

Java Collections framework comes with many implementation classes for the interfaces. Most common implementations are ArrayList, HashMap and HashSet. Java 1.5 included Concurrent implementations; for example ConcurrentHashMap and CopyOnWriteArrayList. Usually Collection classes are not thread-safe and their iterator is fail-fast. In this section, we will learn about commonly used collection classes.

Java Collections框架带有许多接口实现类。 最常见的实现是ArrayList , HashMap和HashSet。 Java 1.5包含并发实现; 例如ConcurrentHashMap和CopyOnWriteArrayList。 通常,Collection类不是线程安全的,并且其迭代器是快速失败的。 在本节中,我们将学习常用的收集类。

4.1)HashSet类 (4.1) HashSet Class)

Java HashSet is the basic implementation the Set interface that is backed by a HashMap. It makes no guarantees for iteration order of the set and permits the null element.

Java HashSet是由HashMap支持的Set接口的基本实现。 它不保证集合的迭代顺序,并允许使用null元素。

This class offers constant time performance for basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. We can set the initial capacity and load factor for this collection. The load factor is a measure of how full the hash map is allowed to get before its capacity is automatically increased.

假定哈希函数将元素正确分散在存储桶remove ,则此类为基本操作( addremovecontainssize )提供恒定的时间性能。 我们可以为此集合设置初始容量和负载因子。 负载因子是散列映射被允许在自动增加其容量之前的填充程度的度量。

4.2)TreeSet类 (4.2) TreeSet Class)

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

基于TreeMap NavigableSet实现。 元素使用其自然顺序进行排序,或通过在设置创建时提供的Comparator排序,具体取决于所使用的构造函数。

Refer: Java Comparable Comparator

参考: Java可比比较器

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

此实现为基本操作(添加,删除和包含)提供了保证的log(n)时间成本。

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

请注意,如果要正确实现Set接口,则由集合(无论是否提供显式比较器)维护的顺序必须与equals一致。 (有关与equals一致的精确定义,请参见Comparable或Comparator。)之所以如此,是因为Set接口是根据equals操作定义的,但是TreeSet实例使用其compareTo(或compare)方法执行所有元素比较,因此两个从集合的角度来看,此方法认为相等的元素是相等的。

4.3)ArrayList类 (4.3) ArrayList Class)

Java ArrayList is the resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

Java ArrayList是List接口的可调整大小的数组实现。 实现所有可选的列表操作,并允许所有元素,包括null。 除了实现List接口之外,此类还提供一些方法来操纵内部用于存储列表的数组的大小。 (此类与Vector大致等效,但它是不同步的。)

The size, isEmpty, get, set, iterator, and list iterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

size isEmpty,get,set,iterator和list迭代器操作在恒定时间内运行。 加法操作以固定的固定时间运行,即,添加n个元素需要O(n)时间。 所有其他操作均以线性时间运行(大致而言)。 与LinkedList实现相比,常数因子较低。

Further reading: Java ArrayList and Iterator

进一步阅读: Java ArrayList和Iterator

4.4)LinkedList类 (4.4) LinkedList Class)

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

List和Deque接口的双链接列表实现。 实现所有可选的列表操作,并允许所有元素(包括null)。

All of the operations perform as expected for a doubly-linked list. Operations that index into the list will traverse the list from the start or the end, whichever is closer to the specified index.

所有操作均按双链表的预期执行。 索引到列表中的操作将从开头或结尾遍历列表,以更接近指定索引的位置为准。

4.5)HashMap类 (4.5) HashMap Class)

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations and permits null values and the null key. HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits null. This class makes no guarantees for the order of the map.

基于哈希表的Map接口的实现。 此实现提供所有可选的映射操作,并允许空值和空键。 HashMap类与Hashtable大致等效,但它是不同步的,并且允许为null。 此类无法保证地图的顺序。

This implementation provides constant-time performance for the basic operations (get and put). It provides constructors to set initial capacity and load factor for the collection.

此实现为基本操作( getput )提供恒定时间的性能。 它为构造函数提供了设置集合的初始容量和负载因子的功能。

Further Read: HashMap vs ConcurrentHashMap

进一步阅读: HashMap与ConcurrentHashMap

4.6)TreeMap类 (4.6) TreeMap Class)

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

基于红黑树的NavigableMap实现。 根据映射键的自然顺序或在映射创建时通过提供的Comparator对映射进行排序,具体取决于所使用的构造函数。

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest’s Introduction to Algorithms.

此实现为containsKey,get,put和remove操作提供了保证的log(n)时间成本。 算法是对Cormen,Leiserson和Rivest的“算法简介”中的算法的改编。

Note that the ordering maintained by a TreeMap, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

请注意,TreeMap维护的排序(与任何排序的映射一样)以及是否提供显式比较器必须与equals一致,如果此排序的映射要正确地实现Map接口。 (有关与equals一致的精确定义,请参见Comparable或Comparator。)之所以这样,是因为Map接口是根据equals操作定义的,但是排序的map使用其compareTo(或compare)方法执行所有键比较。从已排序映射的角度来看,此方法认为相等的键是相等的。 排序后的映射的行为是明确定义的,即使其排序与equals不一致也是如此; 它只是不遵守Map接口的一般约定。

4.7)PriorityQueue类 (4.7) PriorityQueue Class)

Queue processes its elements in FIFO order but sometimes we want elements to be processed based on their priority. We can use PriorityQueue in this case and we need to provide a Comparator implementation while instantiation the PriorityQueue. PriorityQueue doesn’t allow null values and it’s unbounded. For more details about this, please head over to Java Priority Queue where you can check its usage with a sample program.

队列按FIFO顺序处理其元素,但有时我们希望根据元素的优先级对其进行处理。 在这种情况下,我们可以使用PriorityQueue,并且在实例化PriorityQueue时需要提供Comparator实现。 PriorityQueue不允许空值,并且它是无界的。 有关此的更多详细信息,请转到Java Priority Queue ,您可以在其中通过示例程序检查其使用情况。

5.收藏课 (5. Collections class)

Java Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

Java Collections类专门由对集合进行操作或返回集合的静态方法组成。 它包含对集合进行操作的多态算法,“包装器”(包装器),这些包装器返回由指定集合支持的新集合,以及其他一些零碎的东西。

This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse etc.

此类包含用于集合框架算法的方法,例如二进制搜索 ,排序,改组,反向等。

6.同步包装 (6. Synchronized Wrappers)

The synchronization wrappers add automatic synchronization (thread-safety) to an arbitrary collection. Each of the six core collection interfaces — Collection, Set, List, Map, SortedSet, and SortedMap — has one static factory method.

同步包装器将自动同步(线程安全)添加到任意集合。 六个核心集合接口(集合,集合,列表,地图,SortedSet和SortedMap)中的每个都有一个静态工厂方法。

public static  Collection synchronizedCollection(Collection c);
public static  Set synchronizedSet(Set s);
public static  List synchronizedList(List list);
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
public static  SortedSet synchronizedSortedSet(SortedSet s);
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m);

Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection.

这些方法中的每一个都返回一个由指定集合备份的同步(线程安全)集合。

7.不可修改的包装 (7. Unmodifiable wrappers)

Unmodifiable wrappers take away the ability to modify the collection by intercepting all the operations that would modify the collection and throwing an UnsupportedOperationException. Its main usage are;

不可修改的包装器通过拦截所有将修改集合的操作并抛出UnsupportedOperationException ,从而丧失了修改集合的能力。 它的主要用途是;

  • To make a collection immutable once it has been built. In this case, it’s good practice not to maintain a reference to the backing collection. This absolutely guarantees immutability.使集合一旦建立便不可变。 在这种情况下,最好不要保留对后备集合的引用。 这绝对保证了不变性。
  • To allow certain clients read-only access to your data structures. You keep a reference to the backing collection but hand out a reference to the wrapper. In this way, clients can look but not modify, while you maintain full access.允许某些客户端以只读方式访问您的数据结构。 您保留对后备集合的引用,但分发对包装器的引用。 这样,在您保持完全访问权限的同时,客户端可以查看但不能修改。

These methods are;

这些方法是:

public static  Collection unmodifiableCollection(Collection<? extends T> c);
public static  Set unmodifiableSet(Set<? extends T> s);
public static  List unmodifiableList(List<? extends T> list);
public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m);
public static  SortedSet unmodifiableSortedSet(SortedSet<? extends T> s);
public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m);

8.线程安全集合 (8. Thread Safe Collections)

Java 1.5 Concurrent package (java.util.concurrent) contains thread-safe collection classes that allow collections to be modified while iterating. By design iterator is fail-fast and throws ConcurrentModificationException. Some of these classes are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

Java 1.5并发包( java.util.concurrent )包含线程安全的集合类,这些类允许在迭代时修改集合。 通过设计迭代器是快速失败的,并抛出ConcurrentModificationException。 这些类中的一些是CopyOnWriteArrayListConcurrentHashMapCopyOnWriteArraySet

Read these posts to learn about them in more detail.

阅读这些帖子以更详细地了解它们。

  • Avoid ConcurrentModificationException避免ConcurrentModificationException
  • CopyOnWriteArrayList ExampleCopyOnWriteArrayList示例
  • HashMap vs ConcurrentHashMapHashMap与ConcurrentHashMap

9.集合API算法 (9. Collections API Algorithms)

Java Collections Framework provides algorithm implementations that are commonly used such as sorting and searching. Collections class contain these method implementations. Most of these algorithms work on List but some of them are applicable for all kinds of collections.

Java Collections Framework提供了常用的算法实现,例如排序和搜索。 集合类包含这些方法实现。 这些算法大多数都可以在List上使用,但是其中一些算法适用于所有类型的集合。

9.1)排序 (9.1) Sorting)

The sort algorithm reorders a List so that its elements are in ascending order according to an ordering relationship. Two forms of the operation are provided. The simple form takes a List and sorts it according to its elements’ natural ordering. The second form of the sort takes a Comparator in addition to a List and sorts the elements with the Comparator.

排序算法对List进行重新排序,以便其元素按照排序关系升序排列。 提供了两种形式的操作。 简单形式采用一个列表,并根据其元素的自然顺序对其进行排序。 排序的第二种形式除了列表之外还包含一个Comparator,并使用Comparator对元素进行排序。

9.2)改组 (9.2) Shuffling)

The shuffle algorithm destroys any trace of order that may have been present in a List. That is, this algorithm reorders the List based on input from a source of randomness such that all possible permutations occur with equal likelihood, assuming a fair source of randomness. This algorithm is useful in implementing games of chance.

随机播放算法会破坏列表中可能存在的任何顺序跟踪。 即,该算法基于来自随机性源的输入对List进行重新排序,从而假定合理的随机性源,所有可能的排列均以相同的可能性发生。 该算法在实施机会游戏中很有用。

9.3)搜索 (9.3) Searching)

The binarySearch algorithm searches for a specified element in a sorted list. This algorithm has two forms. The first takes a List and an element to search for (the “search key”).

binarySearch算法在排序列表中搜索指定的元素。 该算法有两种形式。 第一个带有一个List和一个要搜索的元素(“搜索关键字”)。

This form assumes that the list is sorted in ascending order according to the natural ordering of its elements.

此格式假定列表根据其元素的自然顺序以升序排序。

The second form takes a Comparator in addition to the List and the search key and assumes that the list is sorted into ascending order according to the specified Comparator.

第二种形式除了列表和搜索键之外还采用一个Comparator,并假定该列表根据指定的Comparator以升序排序。

The sort algorithm can be used to sort the List prior to calling binarySearch.

排序算法可用于在调用binarySearch之前对List进行排序。

9.4)组成 (9.4) Composition)

The frequency and disjoint algorithms test some aspect of the composition of one or more Collections.

频率算法和不相交算法测试一个或多个集合的组成的某些方面。

  • frequency: counts the number of times the specified element occurs in the specified collection频率 :计算指定元素在指定集合中出现的次数
  • disjoint: determines whether two Collections are disjoint; that is, whether they contain no elements in common不相交 :确定两个集合是否不相交; 也就是说,它们是否不包含共同点

9.5)最小值和最大值 (9.5) Min and Max values)

The min and the max algorithms return, respectively, the minimum and maximum element contained in a specified Collection. Both of these operations come in two forms. The simple form takes only a Collection and returns the minimum (or maximum) element according to the elements’ natural ordering.
The second form takes a Comparator in addition to the Collection and returns the minimum (or maximum) element according to the specified Comparator.

最小和最大算法分别返回指定Collection中包含的最小和最大元素。 这两种操作都有两种形式。 简单形式仅采用Collection并根据元素的自然顺序返回最小(或最大)元素。
第二种形式除了Collection之外还采用Comparator,并根据指定的Comparator返回最小(或最大)元素。

10. Java 8 Collections API功能 (10. Java 8 Collections API Features)

Java 8 biggest changes are related to Collection APIs. Some of the important changes and improvements are:

Java 8最大的变化与Collection API有关。 重要的更改和改进包括:

  1. Introduction of Stream API for sequential as well as parallel processing, you should read Java Stream API Tutorial for more details.有关用于顺序处理和并行处理的Stream API的介绍,您应该阅读Java Stream API Tutorial以获得更多详细信息。
  2. Iterable interface has been extended with forEach() default method for iterating over a collection.可迭代接口已使用forEach()默认方法进行了扩展,以迭代集合。
  3. Lambda Expression and Functional interfaces are mostly beneficial with Collection API classes.Lambda表达式和功能性接口最适合Collection API类。

11. Java 10 Collections API的更改 (11. Java 10 Collections API Changes)

  1. List.copyOf, Set.copyOf, and Map.copyOf methods to create unmodifiable collections.List.copyOf,Set.copyOf和Map.copyOf方法,以创建不可修改的集合。
  2. Collectors class gets various methods for collecting unmodifiable collections (Set, List, Map). These method names are toUnmodifiableList, toUnmodifiableSet, and toUnmodifiableMap.Collectors类获取用于收集不可修改的集合(Set,List,Map)的各种方法。 这些方法名称为toUnmodifiableList,toUnmodifiableSet和toUnmodifiableMap。

Let’s look at an example of these new Java 10 Collections API methods usage.

让我们看一下这些新的Java 10 Collections API方法用法的示例。

package com.journaldev.collections;import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;public class JDK10CollectionFunctions {public static void main(String[] args) {// 1. List, Set, Map copyOf(Collection) methodList<String> actors = new ArrayList<>();actors.add("Jack Nicholson");actors.add("Marlon Brando");System.out.println(actors);// prints [Jack Nicholson, Marlon Brando]// New API added - Creates an UnModifiable List from a List.List<String> copyOfActors = List.copyOf(actors);System.out.println(copyOfActors);// prints [Jack Nicholson, Marlon Brando]// copyOfActors.add("Robert De Niro"); Will generate// UnsupportedOperationExceptionactors.add("Robert De Niro");System.out.println(actors);// prints [Jack Nicholson, Marlon Brando, Robert De Niro]System.out.println(copyOfActors);// prints [Jack Nicholson, Marlon Brando]// 2. Collectors class toUnmodifiableList, toUnmodifiableSet, and// toUnmodifiableMap methodsList<String> collect = actors.stream().collect(Collectors.toUnmodifiableList());System.out.println(collect);}}

12. Java 11 Collections API的更改 (12. Java 11 Collections API Changes)

A new default method toArray(IntFunction<T[]> generator) added in the Collection interface. This method returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

在Collection接口中添加了一个新的默认方法toArray(IntFunction<T[]> generator) 。 此方法使用提供的生成器函数分配返回的数组,该数组返回包含此集合中所有元素的数组。

package com.journaldev.collections;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;public class JDK11CollectionFunctions {public static void main(String[] args) {/** JDK 11 New Method in Collection interface * default <T> T[] toArray(IntFunction<T[]> generator) {* return toArray(generator.apply(0)); }*/List<String> strList = new ArrayList<>();strList.add("Java");strList.add("Python");strList.add("Android");String[] strArray = strList.toArray(size -> new String[size]);System.out.println(Arrays.toString(strArray));strArray = strList.toArray(size -> new String[size + 5]);System.out.println(Arrays.toString(strArray));strArray = strList.toArray(size -> new String[size * 3]);System.out.println(Arrays.toString(strArray));}}

Output:

输出:

[Java, Python, Android]
[Java, Python, Android, null, null]
[Java, Python, Android]

13.简而言之集合类 (13. Collection classes in a Nutshell)

Below table provides basic details of commonly used collection classes.

下表提供了常用集合类的基本详细信息。

Download URL: Java Collection Classes

下载URL : Java集合类

Collection Ordering Random Access Key-Value Duplicate Elements Null Element Thread Safety
ArrayList
LinkedList
HashSet
TreeSet
HashMap
TreeMap
Vector
Hashtable
Properties
Stack
CopyOnWriteArrayList
ConcurrentHashMap
CopyOnWriteArraySet
采集 定购 随机访问 核心价值 重复元素 空元素 线程安全
数组列表
链表
哈希集
树集
哈希图
树状图
向量
哈希表
物产
叠放
CopyOnWriteArrayList
并发哈希图
CopyOnWriteArraySet

I hope this tutorial explains most of the topics in java collections framework, please share your opinion with comments.

我希望本教程能够解释Java Collections框架中的大多数主题,请在评论中分享您的观点。

Reference: Oracle Documentation

参考: Oracle文档

翻译自: https://www.journaldev.com/1260/collections-in-java-tutorial

java集合替换集合

java集合替换集合_Java集合–您必须知道的13件事相关推荐

  1. 所有C#程序员必须知道的13件事

    1.发展进程 开发过程是bug和缺陷开始的地方.在发布之前,利用帮助您避免或发现这些问题的工具: 编码标准 标准的一致使用可以导致更易于维护的代码,特别是在由多个开发人员或团队编写和维护的代码库中.F ...

  2. friends迷必须知道的114件事

    friends迷必须知道的114件事- - (贴点无关的娱乐,呵呵!) 1.<老友记>第一季第一集的播放日期是1994年9月22日,剧中第一句对活是莫尼卡说的.她说:"这没有什么 ...

  3. 歪果仁眼中的中国科技界必须知道的7件事

    注:本文来自Medium, 中文版由天地会珠海分舵编译.文章中有些观点可能存在偏颇,请读者自行决断. 中国是个神奇的国度,有很多东西是歪果仁所不知道的.以下列出在中国科技界你必须知道的7个事实. 中国 ...

  4. 每一个C#开发者必须知道的13件事情

    1.开发流程 程序的Bug与瑕疵往往出现于开发流程当中.只要对工具善加利用,就有助于在你发布程序之前便将问题发现,或避开这些问题. 标准化代码书写 标准化代码书写可以使代码更加易于维护,尤其是在代码由 ...

  5. 关于DevOps你必须知道的11件事

    本文转载于Infoq,虽然是几年前的文章,确实是非常好的一篇文章. 作者 Gene Kim ,译者 戚一品 Infoq链接:http://www.infoq.com/cn/articles/11dev ...

  6. 有理想的程序员必须知道的15件事

    作为程序员,要取得非凡成就需要记住的15件事. 1.走一条不一样的路 在有利于自己的市场中竞争,如果你满足于"泯然众人矣",那恐怕就得跟那些低工资国家的程序员们同场竞技了. 2.了 ...

  7. 开展性能测试必须知道的21件事:认清性能问题

    近年来大家都开始关注移动应用性能管理和性能监测,我们找到一位国外资深的开发者对性能的相关理论,希望各位喜欢. 1. 公理化方法 当我在1989年加入 oracle 公司时,解决性能问题(人们通常说的 ...

  8. MySQL中你必须知道的10件事,1.5万字!

    攻击性不大,侮辱性极强 1.SQL语句执行流程 MySQL大体上可分为Server层和存储引擎层两部分. Server层: 连接器:TCP握手后服务器来验证登陆用户身份,A用户创建连接后,管理员对A用 ...

  9. 程序员必须知道的15件事(转)

    1.走一条不一样的路 在有利于自己的市场中竞争,如果你满足于"泯然众人矣",那恐怕就得跟那些低工资国家的程序员们同场竞技了. 2.了解自己的公司 以我在医院.咨询公司.物流企业以及 ...

最新文章

  1. tf.variance_scaling_initializer() tensorflow学习:参数初始化
  2. 2016年云安全调查报告(更新版)
  3. JavaScript实现放大镜功能
  4. VScode 乱装插件环境破坏踩坑自我反思总结
  5. conda init 关闭和重启shell_TP5实战源码 通过shell建立PHP守护程序
  6. Microsoft Exchange 2010 安装配置
  7. libxml中用到的Xpath语法说明
  8. JS(去掉前后空格或去掉所有空格)的用法
  9. zune linux_快速提示:在出售Zune HD之前,先擦除所有内容
  10. 基于mono和C#运行的cms产品
  11. 百度CTO王海峰出席科协年会重头论坛,展现智能云产业智能化硕果
  12. Layui中的table中toolbar自定义过程
  13. python少儿编程教案_超好玩的Python少儿编程
  14. 计算机应用基础项目化教程ppt,计算机应用基础项目化教程_课件
  15. 网站如何被百度蜘蛛快速抓取?
  16. Web2.0与Web3.0的区别是什么
  17. r语言ggplot2误差棒图快速指南
  18. 1bit与2bit字符——简单模拟题
  19. arcgis 线段合并
  20. Linux安装Rar软件与压缩、解压方法

热门文章

  1. 初探Bootstrap
  2. MATLAB中zero和ones函数(转载)
  3. jmeter正则中常见的转义字符-笔记三
  4. web自动化测试python+selenium学习总结----selenium安装、浏览器驱动下载
  5. ng的概念层次(官方文档摘录)
  6. 带你玩转JavaWeb开发之四 -如何用JS做登录注册页面校验
  7. 开发常用技巧之css字体编码
  8. FileSystemObject操作文件的权限问题
  9. 《游戏人工智能编程》读书笔记 —— 向量的归一和点乘
  10. IKVM.NET_第一篇_概述