The List Interface
A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection , the List interface includes operations for the following:
- Positional access — manipulates elements based on their numerical position in the list. This includes methods such as get , set , add , addAll , and remove .
- Search — searches for a specified object in the list and returns its numerical position. Search methods include indexOf and lastIndexOf .
- Iteration — extends Iterator semantics to take advantage of the list's sequential nature. The listIterator methods provide this behavior.
- Range-view — The sublist method performs arbitrary range operations on the list.
The Java platform contains two general-purpose List implementations. ArrayList , which is usually the better-performing implementation, and LinkedList which offers better performance under certain circumstances.
Collection Operations
The operations inherited from Collection all do about what you'd expect them to do, assuming you're already familiar with them. If you're not familiar with them from Collection , now would be a good time to read The Collection Interface section. The remove operation always removes the first occurrence of the specified element from the list. The add and addAll operations always append the new element(s) to the end of the list. Thus, the following idiom concatenates one list to another.
Here's a nondestructive form of this idiom, which produces a third List consisting of the second list appended to the first.
Note that the idiom, in its nondestructive form, takes advantage of ArrayList 's standard conversion constructor.
And here’s an example (JDK 8 and later) that aggregates some names into a List :
Like the Set interface, List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. Two List objects are equal if they contain the same elements in the same order.
Positional Access and Search Operations
The basic positional access operations are get , set , add and remove . (The set and remove operations return the old value that is being overwritten or removed.) Other operations ( indexOf and lastIndexOf ) return the first or last index of the specified element in the list. Vector ( elementAt , setElementAt , insertElementAt , and removeElementAt ) with one noteworthy exception: The set and remove operations return the old value that is being overwritten or removed; the Vector counterparts ( setElementAt and removeElementAt ) return nothing ( void ). The search operations indexOf and lastIndexOf behave exactly like the identically named operations in Vector . —>
The addAll operation inserts all the elements of the specified Collection starting at the specified position. The elements are inserted in the order they are returned by the specified Collection 's iterator. This call is the positional access analog of Collection 's addAll operation.
Here's a little method to swap two indexed values in a List .
Of course, there's one big difference. This is a polymorphic algorithm: It swaps two elements in any List , regardless of its implementation type. Here's another polymorphic algorithm that uses the preceding swap method.
This algorithm, which is included in the Java platform's Collections class, randomly permutes the specified list using the specified source of randomness. It's a bit subtle: It runs up the list from the bottom, repeatedly swapping a randomly selected element into the current position. Unlike most naive attempts at shuffling, it's fair (all permutations occur with equal likelihood, assuming an unbiased source of randomness) and fast (requiring exactly list.size()-1 swaps). The following program uses this algorithm to print the words in its argument list in random order.
In fact, this program can be made even shorter and faster. The Arrays class has a static factory method called asList , which allows an array to be viewed as a List . This method does not copy the array. Changes in the List write through to the array and vice versa. The resulting List is not a general-purpose List implementation, because it doesn't implement the (optional) add and remove operations: Arrays are not resizable. Taking advantage of Arrays.asList and calling the library version of shuffle , which uses a default source of randomness, you get the following tiny program whose behavior is identical to the previous program.
Iterators
As you'd expect, the Iterator returned by List 's iterator operation returns the elements of the list in proper sequence. List also provides a richer iterator, called a ListIterator , which allows you to traverse the list in either direction, modify the list during iteration, and obtain the current position of the iterator.
ListIterator interface follows.
The three methods that ListIterator inherits from Iterator ( hasNext , next , and remove ) do exactly the same thing in both interfaces. The hasPrevious and the previous operations are exact analogues of hasNext and next . The former operations refer to the element before the (implicit) cursor, whereas the latter refer to the element after the cursor. The previous operation moves the cursor backward, whereas next moves it forward.
Here's the standard idiom for iterating backward through a list.
Note the argument to listIterator in the preceding idiom. The List interface has two forms of the listIterator method. The form with no arguments returns a ListIterator positioned at the beginning of the list; the form with an int argument returns a ListIterator positioned at the specified index. The index refers to the element that would be returned by an initial call to next . An initial call to previous would return the element whose index was index-1 . In a list of length n , there are n+1 valid values for index , from 0 to n , inclusive.
Intuitively speaking, the cursor is always between two elements — the one that would be returned by a call to previous and the one that would be returned by a call to next . The n+1 valid index values correspond to the n+1 gaps between elements, from the gap before the first element to the gap after the last one. The following figure shows the five possible cursor positions in a list containing four elements.
The five possible cursor positions.
Calls to next and previous can be intermixed, but you have to be a bit careful. The first call to previous returns the same element as the last call to next . Similarly, the first call to next after a sequence of calls to previous returns the same element as the last call to previous .
It should come as no surprise that the nextIndex method returns the index of the element that would be returned by a subsequent call to next , and previousIndex returns the index of the element that would be returned by a subsequent call to previous . These calls are typically used either to report the position where something was found or to record the position of the ListIterator so that another ListIterator with identical position can be created.
It should also come as no surprise that the number returned by nextIndex is always one greater than the number returned by previousIndex . This implies the behavior of the two boundary cases: (1) a call to previousIndex when the cursor is before the initial element returns -1 and (2) a call to nextIndex when the cursor is after the final element returns list.size() . To make all this concrete, the following is a possible implementation of List.indexOf .
Note that the indexOf method returns it.previousIndex() even though it is traversing the list in the forward direction. The reason is that it.nextIndex() would return the index of the element we are about to examine, and we want to return the index of the element we just examined.
The Iterator interface provides the remove operation to remove the last element returned by next from the Collection . For ListIterator , this operation removes the last element returned by next or previous . The ListIterator interface provides two additional operations to modify the list — set and add . The set method overwrites the last element returned by next or previous with the specified element. The following polymorphic algorithm uses set to replace all occurrences of one specified value with another.
The only bit of trickiness in this example is the equality test between val and it.next . You need to special-case a val value of null to prevent a NullPointerException .
The add method inserts a new element into the list immediately before the current cursor position. This method is illustrated in the following polymorphic algorithm to replace all occurrences of a specified value with the sequence of values contained in the specified list.
Range-View Operation
The range-view operation, subList(int fromIndex, int toIndex) , returns a List view of the portion of this list whose indices range from fromIndex , inclusive, to toIndex , exclusive. This half-open range mirrors the typical for loop.
As the term view implies, the returned List is backed up by the List on which subList was called, so changes in the former are reflected in the latter.
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a List can be used as a range operation by passing a subList view instead of a whole List . For example, the following idiom removes a range of elements from a List .
Similar idioms can be constructed to search for an element in a range.
Note that the preceding idioms return the index of the found element in the subList , not the index in the backing List .
Any polymorphic algorithm that operates on a List , such as the replace and shuffle examples, works with the List returned by subList .
Here's a polymorphic algorithm whose implementation uses subList to deal a hand from a deck. That is, it returns a new List (the "hand") containing the specified number of elements taken from the end of the specified List (the "deck"). The elements returned in the hand are removed from the deck.
Note that this algorithm removes the hand from the end of the deck. For many common List implementations, such as ArrayList , the performance of removing elements from the end of the list is substantially better than that of removing elements from the beginning.
The following is a program that uses the dealHand method in combination with Collections.shuffle to generate hands from a normal 52-card deck. The program takes two command-line arguments: (1) the number of hands to deal and (2) the number of cards in each hand.
Running the program produces output like the following.
Although the subList operation is extremely powerful, some care must be exercised when using it. The semantics of the List returned by subList become undefined if elements are added to or removed from the backing List in any way other than via the returned List . Thus, it's highly recommended that you use the List returned by subList only as a transient object — to perform one or a sequence of range operations on the backing List . The longer you use the subList instance, the greater the probability that you'll compromise it by modifying the backing List directly or through another subList object. Note that it is legal to modify a sublist of a sublist and to continue using the original sublist (though not concurrently).
List Algorithms
Most polymorphic algorithms in the Collections class apply specifically to List . Having all these algorithms at your disposal makes it very easy to manipulate lists. Here's a summary of these algorithms, which are described in more detail in the Algorithms section.
Руководство Java Collections Framework
Следуйте за нами на нашей фан-странице, чтобы получать уведомления каждый раз, когда появляются новые статьи. Facebook
1- Введение

2- Первый пример
3- Лимиты при использовании массива — Предложение решения проблемы.
3.1- Массив — стандартный набор.
- Массив является стандартным и знакомым.
- хранит ссылочный вид, примитивные виды
- int[] myArray=new int[]<1,4,3>;
- Object[] myArrayObj =new Object[]<"Object",new Integer(100)>;
- Это затрудняет расширение массива
- Это затрудняет удаления элемента из массива.
3.2- Удаление элемента из массива.
Элементы массива расставлены поочередно в памяти, это сложность, когда вы намеренно удаляете определенный элемент в массиве, он теряет свою очередность. Обычно, используется техника создания нового массива для хранения объектов старого массива и убрать ненужные элементы, но это снижает эффективность программы. В случае расширения массива используется индентичная техника, это создать новый массив с большим размером, потом скопировать элементы старого массива в новый массив.
Очевидно, что массив это не хороший способ для разных случаев применения.
3.3- Связанный список
Связанный список (Linked List) это один из способов управления списка данных, который поборол недостаток массива. Конечно для управления списком в Java есть многие другие способы, например ArrayList.
Смотрите недостатки LinkedList:
- Элементы в этом списке могут быть прерывисто изолированы (непостоянны) в памяти.
- Это двустороняя связь между элементами.
- Каждый элемент в списке имеет ссылку к элементу напротив и к элементу сзади.
4- Обзор Java Collections Framework
4.1- Интерфейсы в Java Collections Framework
4.2- Две иерархии лидируемые 2 интерфейсами Collection и Map — Методы хранения данных
- Группа Collection хранит объекты.
- Есть 3 подветки в группе Collection: Queue, List, Set .
- Элементы могут быть похожими или независят от 3-х перечисленных веток. (Более детально будет обсуждено позже) .
- Пары key/value содержащиеся в Map (карта) это всегда разные key между парами
- Если мы знаем key, можем получить значение value в Map соответстующий с этим key.
4.3- Интерфейсы итератора и интерфейс RandomAccess — Метод получения доступа к данным
- java.util.Iterator
- Похож на итератор для получения данных, способ запроса по очереди с одного элемента к другому.
- Случайный метод запроса, например для позиции элемента и получения этого элемента в наборе
- Например java.util.Vector применяет этот интерфейс, может получить случайный элемент vector.get(int index).
- java.util.Collection расширен из интерфейса java.lang.Iterable (может повториться) поэтому унаследовал метод public Iterator<E> iterator().
Vector принадлежит группе Collection, вы можете получить доступ к ее элементам через Iterator и можно получить случайный доступ через метод get(index).
Заметка: Для объектов в группе List вы так же можете получить объект ListIterator, этот итератор позволяет вам переместить назад или вперед позицию курсора на списке, вместо того чтобы перемещать только вперед как в Iterator.
5- Collection Group
5.1- Interfaces в группе Collection
5.2- java.util.Collection Interface
5.3- Получить доступ к элементам коллекции


5.4- Подветка Collection
java.util.Queue java.util.List java.util.Set Разрешает содержать дублированные элементы Разрешает содержать дублированные элементы Не разрешает содержать дублированные элементы Не разрешает содержать элементы null Разрешает содержать один или более элементы null Смотря по классу, выполняет Set поддерживающий элементы null или нет. Если поддерживает, то содержит только один элемент null 
Set это неупорядоченный набор, и не позволяет содержать дубликаты. Вы не може сказать про N-ый элемент и даже про первый элемент, так как он не имеет порядок. Вы можете добавить или удалить элементы, и можете найти если элемент существует (Например "Находится ли 7 в данном наборе?").
Примечание: SortedSet это подинтерфейс Set который может содержать элементы, имеющие порядок.
5.5- java.util.List Interface
- Позволяет дублирование элементов
- Позволяет сущетвовать 0 или более элементов null.
- Это набор с последовательностью

5.6- java.util.Set Interface
- Описывает набор который не позволяет содержать дублированные элементы
- Позволяет существование элемента null, если есть элемент null то только 1.
5.7- java.util.Queue Interface
- Это коллекция позволяющия элементам дублироваться.
- Не позволяет существовать элементам null.
- java.util.LinkedList
- java.util.PriorityQueue
LinkedList это стандартная очередь. Но помните, что LinkedList применяет оба интерфейса List и Queue.
PriorityQueue хранит элементы внутри по естественному порядку элементов (если эти элементы вида Comparable), или в соответствии с Comparator настроенный для PriorityQueue.
Throws exception Returns special value Insert add(e) offer(e) Remove remove() poll() Examine element() peek() 





5.8- Наследственные отношения между классами в группе Collection

5.9- java.util.ArrayList
5.10- java.util.Vector
Vector это класс имеющий функции похожие на ArrayList. Отличие в том, что методы Vector синхронизированы, а в ArrayList нет.
5.11- java.util.SortedSet
SortedSet это подинтерфейс интерфейса Set, который имеет полные функции Set. SortedSet это категория наборов с расстановкой, добавленные новые элементы в категорию набора автоматически стоят на подходящем месте, чтобы удостовериться, что набор расставлен (по возрастанию или убыванию)
Поэтому элементы набора должны сравниваться друг с другом, они должны быть объектами java.lang.Comparable (Могут быть сравнены), Если вы добавляете элемент который не является объектом Comparable, вы получите исключение.

Будем считать класс Player (Игрок), включает информацию: имя, фамилия, количество золотых медалей, количество серебряных медалей, количество бронзовых медалей.
- У кого больше золотых медалей будет иметь позицию выше.
- Если у двух человек количество золотых медалей равно, то у кого будет больше серебряных медалей, имеет позицию выше.
- Если у двух человек количество золотых серебряных медалей равно, то у кого будет больше бронзовых медалей, имеет позицию выше.
- Остальные будут считаться равными.
6- Группа Map
6.1- Interfaces в группе Map
6.2- Классы в группе Map

6.3- java.util.Map Interface
SN Methods with Description 1 void clear( ) Removes all key/value pairs from the invoking map.(optional operation).
Returns true if the invoking map contains k as a key. Otherwise, returns false.
Returns true if the map contains v as a value. Otherwise, returns false
Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map.
Returns true if obj is a Map and contains the same entries. Otherwise, returns false.
Returns the value associated with the key k.
Returns the hash code for the invoking map.
Returns true if the invoking map is empty. Otherwise, returns false.
Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map.
Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned.(optional operation).
Puts all the entries from m into this map.(optional operation).
Removes the entry whose key equals k. (optional operation).
Returns the number of key/value pairs in the map.
Returns a collection containing the values in the map. This method provides a collection-view of the values in the map.

6.4- java.util.SortedMap Interface
SN Methods with Description 1 Comparator comparator( ) Returns the invoking sorted map's comparator. If the natural ordering is used for the invoking map, null is returned.
Returns the first key in the invoking map.
Returns a sorted map for those map entries with keys that are less than end.
Returns the last key in the invoking map.
Returns a map containing those entries with keys that are greater than or equal to start and less than end
Returns a map containing those entries with keys that are greater than or equal to start.
View more Tutorials:
Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.

Learn and Understand Interfaces in C#
Learn SQL, PHP-PDO, JavaScript and Bootstrap for web apps
Learn Database Design using MongoDB from Scratch
Learn Bootstrap 4 The Complete Guide by Building 8 Projects
Learning JavaScript Programming Tutorial. A Definitive Guide
Advance Android Programming — learning beyond basics
Java Spring and Hibernate:create a crud application
Create Complete Web Applications easily with APEX 5
CSS3 MasterClass — Transformations And Animations
Servlets and JSPs Tutorial: Learn Web Applications With Java
Learning Oracle Application Express ( Oracle Apex ) Training
Full Stack Mobile Developer course ( iOS 11, and Android O )
Introduction to Oracle Database Backup and Security
The Complete TDD Course: Master Ruby Development with RSpec
Concepts of Object Oriented Programming with C++
Responsive Web Design with HTML5 and CSS3 — Introduction
JSP (Java server pages), Servlet & JSTL tutorial (J2EE)
Learn Partitioning in PostgreSQL from Scratch
iOS 13 — How to Make Amazing iPhone Apps: Xcode 11 & Swift 5
MongoDB: Learn Administration and Security in MongoDB
Master AngularJS : Learn Angular JS From Scratch
Interactive JavaScript DOM Introduction to the DOM Course
Flutter Blog app Using Firestore Build ios & Android App
MySQL Made Simple For Beginners
Backup and Restore Fundamentals in PostgreSQL DB — Level 1
Обращение к элементам списка
Доброго времени суток. Есть класс с 2-мя полями типа String. На основе этого класса создан список (ArrayList). Как обращаться к элементам этого списка?
Ответ: list.get(0).name, где name поле из класса.
Доброго времени суток!
Для того, чтобы обращаться к данным элемента списка по указанному индексу необходимо использовать метод get(int index) , который возвращает объект типа, указанного при объявлении списка. Далее Вам просто будет необходимо использовать полученный объект и выполнять необходимые действия.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Справочник по Java Collections Framework
Данная публикация не является полным разбором или анализом (не покрывает пакет java.util.concurrent ). Это, скорее, справочник, который поможет начинающим разработчикам понять ключевые отличия одних коллекций от других, а более опытным разработчикам просто освежить материал в памяти.
Что такое Java Collections Framework?
Java Collection Framework — иерархия интерфейсов и их реализаций, которая является частью JDK и позволяет разработчику пользоваться большим количесвом структур данных из «коробки».
Базовые понятия
На вершине иерархии в Java Collection Framework располагаются 2 интерфейса: Collection и Map . Эти интерфейсы разделяют все коллекции, входящие во фреймворк на две части по типу хранения данных: простые последовательные наборы элементов и наборы пар «ключ — значение» (словари).
Collection — этот интерфейс находится в составе JDK c версии 1.2 и определяет основные методы работы с простыми наборами элементов, которые будут общими для всех его реализаций (например size() , isEmpty() , add(E e) и др.). Интерфейс был слегка доработан с приходом дженериков в Java 1.5. Также, в версии Java 8, было добавлено несколько новых методов для работы с лямбдами (такие как stream() , parallelStream() , removeIf(Predicate<? super E> filter) и др.).
Важно также отметить, что эти методы были реализованы непосредственно в интерфейсе как default -методы.
Map. Данный интерфейс также находится в составе JDK c версии 1.2 и предоставляет разработчику базовые методы для работы с данными вида «ключ — значение».Также как и Collection , он был дополнен дженериками в версии Java 1.5 и в версии Java 8 появились дополнительные методы для работы с лямбдами, а также методы, которые зачастую реализовались в логике приложения ( getOrDefault(Object key, V defaultValue) , putIfAbsent(K key, V value) ).
Интерфейс Map [doc]

Hashtable — реализация такой структуры данных, как хэш-таблица. Она не позволяет использовать null в качестве значения или ключа. Эта коллекция была реализована раньше, чем Java Collection Framework, но в последствии была включена в его состав. Как и другие коллекции из Java 1.0, Hashtable является синхронизированной (почти все методы помечены как synchronized ). Из-за этой особенности у неё имеются существенные проблемы с производительностью и, начиная с Java 1.2, в большинстве случаев рекомендуется использовать другие реализации интерфейса Map ввиду отсутствия у них синхронизации.
HashMap — коллекция является альтернативой Hashtable . Двумя основными отличиями от Hashtable являются то, что HashMap не синхронизирована и HashMap позволяет использовать null как в качестве ключа, так и значения. Так же как и Hashtable , данная коллекция не является упорядоченной: порядок хранения элементов зависит от хэш-функции. Добавление элемента выполняется за константное время O(1), но время удаления, получения зависит от распределения хэш-функции. В идеале является константным, но может быть и линейным O(n). Более подробную информацию о HashMap можно почитать здесь (актуально для Java < 8).
LinkedHashMap — это упорядоченная реализация хэш-таблицы. Здесь, в отличии от HashMap , порядок итерирования равен порядку добавления элементов. Данная особенность достигается благодаря двунаправленным связям между элементами (аналогично LinkedList ). Но это преимущество имеет также и недостаток — увеличение памяти, которое занимет коллекция. Более подробная информация изложена в этой статье.
TreeMap — реализация Map основанная на красно-чёрных деревьях. Как и LinkedHashMap является упорядоченной. По-умолчанию, коллекция сортируется по ключам с использованием принципа «natural ordering», но это поведение может быть настроено под конкретную задачу при помощи объекта Comparator , который указывается в качестве параметра при создании объекта TreeMap .
WeakHashMap — реализация хэш-таблицы, которая организована с использованием weak references. Другими словами, Garbage Collector автоматически удалит элемент из коллекции при следующей сборке мусора, если на ключ этого элеметна нет жёстких ссылок.
Интерфейс List [doc]

Реализации этого интерфейса представляют собой упорядоченные коллекции. Кроме того, разработчику предоставляется возможность доступа к элементам коллекции по индексу и по значению (так как реализации позволяют хранить дубликаты, результатом поиска по значению будет первое найденное вхождение).
Vector — реализация динамического массива объектов. Позволяет хранить любые данные, включая null в качестве элемента. Vector появился в JDK версии Java 1.0, но как и Hashtable , эту коллекцию не рекомендуется использовать, если не требуется достижения потокобезопасности. Потому как в Vector , в отличии от других реализаций List , все операции с данными являются синхронизированными. В качестве альтернативы часто применяется аналог — ArrayList .
Stack — данная коллекция является расширением коллекции Vector . Была добавлена в Java 1.0 как реализация стека LIFO (last-in-first-out). Является частично синхронизированной коллекцией (кроме метода добавления push() ). После добавления в Java 1.6 интерфейса Deque , рекомендуется использовать именно реализации этого интерфейса, например ArrayDeque .
ArrayList — как и Vector является реализацией динамического массива объектов. Позволяет хранить любые данные, включая null в качестве элемента. Как можно догадаться из названия, его реализация основана на обычном массиве. Данную реализацию следует применять, если в процессе работы с коллекцией предплагается частое обращение к элементам по индексу. Из-за особенностей реализации поиндексное обращение к элементам выполняется за константное время O(1). Но данную коллекцию рекомендуется избегать, если требуется частое удаление/добавление элементов в середину коллекции. Подробный анализ и описание можно почитать в этом хабратопике.
LinkedList — ещё одна реализация List . Позволяет хранить любые данные, включая null . Особенностью реализации данной коллекции является то, что в её основе лежит двунаправленный связный список (каждый элемент имеет ссылку на предыдущий и следующий). Благодаря этому, добавление и удаление из середины, доступ по индексу, значению происходит за линейное время O(n), а из начала и конца за константное O(1). Так же, ввиду реализации, данную коллекцию можно использовать как стек или очередь. Для этого в ней реализованы соответствующие методы. На Хабре также есть статья с подробным анализом и описанием этой коллекции.
Интерфейс Set [doc]

Представляет собой неупорядоченную коллекцию, которая не может содержать дублирующиеся данные. Является программной моделью математического понятия «множество».
HashSet — реализация интерфейса Set , базирующаяся на HashMap . Внутри использует объект HashMap для хранения данных. В качестве ключа используется добавляемый элемент, а в качестве значения — объект-пустышка (new Object()). Из-за особенностей реализации порядок элементов не гарантируется при добавлении.
LinkedHashSet — отличается от HashSet только тем, что в основе лежит LinkedHashMap вместо HashMap . Благодаря этому отличию порядок элементов при обходе коллекции является идентичным порядку добавления элементов.
TreeSet — аналогично другим классам-реализациям интерфейса Set содержит в себе объект NavigableMap , что и обуславливает его поведение. Предоставляет возможность управлять порядком элементов в коллекции при помощи объекта Comparator , либо сохраняет элементы с использованием «natural ordering».
Интерфейс Queue [doc]

Этот интерфейс описывает коллекции с предопределённым способом вставки и извлечения элементов, а именно — очереди FIFO (first-in-first-out). Помимо методов, определённых в интерфейсе Collection, определяет дополнительные методы для извлечения и добавления элементов в очередь. Большинство реализаций данного интерфейса находится в пакете java.util.concurrent и подробно рассматриваются в данном обзоре.
PriorityQueue — является единственной прямой реализацией интерфейса Queue (была добавлена, как и интерфейс Queue, в Java 1.5), не считая класса LinkedList , который так же реализует этот интерфейс, но был реализован намного раньше. Особенностью данной очереди является возможность управления порядком элементов. По-умолчанию, элементы сортируются с использованием «natural ordering», но это поведение может быть переопределено при помощи объекта Comparator , который задаётся при создании очереди. Данная коллекция не поддерживает null в качестве элементов.
ArrayDeque — реализация интерфейса Deque, который расширяет интерфейс Queue методами, позволяющими реализовать конструкцию вида LIFO (last-in-first-out). Интерфейс Deque и реализация ArrayDeque были добавлены в Java 1.6. Эта коллекция представляет собой реализацию с использованием массивов, подобно ArrayList , но не позволяет обращаться к элементам по индексу и хранение null . Как заявлено в документации, коллекция работает быстрее чем Stack , если используется как LIFO коллекция, а также быстрее чем LinkedList, если используется как FIFO.
Заключение
Java Collections Framework содержит большое количество различных структур данных, доступных в JDK «из коробки», которые в большинстве случаев покрывают все потребности при реализации логики приложения. Сравнение временных характеристик основных коллекций, которые зачастую используются в разработке приложений приведено в таблице:

При необходимости, разработчик может создать собственную реализацию, расширив или переопределив существующую логику, либо создав свою собственную реализацию подходящего интерфейса с нуля. Также существует некоторое количество готовых решений, которые являются альтернативой или дополнением к Java Collections Framework. Наиболее популярными являются Google Guava и Commons Collections.