Home  >  Article  >  Java  >  Collection in Java

Collection in Java

Susan Sarandon
Susan SarandonOriginal
2024-10-18 06:16:30825browse

Collection in Java

The collection hierarchy in Java consists of grouping elements/objects, where each class has subclasses and methods. It does not accept primitive types, but the "array" class allows the inclusion of several homogeneous elements of the same type, accepting primitive types.

The collections framework methods are present in the java.util package within the JDK (Java Development Kit). The main interfaces are List, Set and Map.

Generics
Use the symbol <> (diamond) for generic types. The most common type parameters include E (Element), K (Key), N (Number), T (Type), V (Value).

Comparator x Comparable

They are used for ordering collections. Comparable provides a single ordering sequence, affecting the original class, while Comparator provides multiple sequences without modifying the original class.

List x Set x Map

  1. List: Allows duplicate elements, maintains insertion order. Examples of implementations are ArrayList and LinkedList.
  2. Set: Does not allow duplicate elements.
  3. HashSet uses hash table
  4. TreeSet uses balanced binary tree
  5. LinkedHashSet maintains insertion order
  6. Map: Maps keys to values.
  7. HashMap uses hash table
  8. TreeMap uses balanced binary tree
  9. LinkedHashMap maintains insertion order

Examples of implementations/Classes:

  • ArrayList: Stores elements in a resizable array, allowing quick access by indexes.
  • LinkedList: Stores elements in a doubly linked list, efficient for addition/removal at the beginning/end.
  • HashSet: Stores elements in a hash table, in no specific order.
  • TreeSet: Stores elements in a balanced binary tree, maintaining ascending order.
  • LinkedHashSet: Maintains insertion order using hash table and doubly linked list.
  • HashMap: Maps keys to values ​​using hash table, in no specific order.

Observations:
The first element added to a Set is the first to be returned.
In Map, the put method updates or creates a key-value pair.
The Map interface does not require the creation of a class before creating a collection, and the search can be done directly by key, eliminating the need for for loops.
Examples of older implementations include Vector (synchronized) and HashTable (synchronized and not allowing nulls).

The above is the detailed content of Collection in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Item Beware of string concatenation performanceNext article:None