Hello, today for everyone to share is Java collection, quickly take out a small notebook to write down

Collections in Java

Collections: A storage structure that can store multiple data dynamically. A common API provided by Java, available in the java.util package

The architecture of the entire Java collection is as follows:

There are two main branches:

  • A Collection can store only one value at a time

Set stores elements that are unordered and not duplicated.

  1. HashSet unordered non-repeating collection
  2. LinkedHashSet an order that is not repeated is achieved through a linked list

List stores elements in order and can be repeated common implementation classes are:

  1. The underlying implementation of ArrayList is an array. It is efficient to read but inefficient to modify
  2. The bottom layer of LinkedList is realized by bidirectional LinkedList. The modification efficiency is high, but the reading efficiency is low

The Map needs to store one key-value pair at a time

The commonly used implementation class HashMap

Collection

Iterator

Iterator is the parent of a Collection and provides an internal way to iterate over collections of the Collection type

Common methods:

  • HasNext () checks to see if the next position of the current pointer has an element and returns true if so, false otherwise
  • Next () moves the pointer to the next element and retrieves it to return to the caller
  • Remove () removes the pointer currently traversed

Since JDK5, all Iterator variables can be traversed using forEach

The Set interface

The Set interface is a subinterface type of Collection, which is characterized by unordered and non-repetitive

A Set corresponds to the concept of a Set in mathematics

How to determine if elements in a Set are duplicated:

  1. The value returned by the hashCode() method of this object is equal. If the value is equal, the two objects are equal
  2. When hashCode() returns equal values, the equals() method is used to determine whether the current two objects are equal. If they are equal, the store is skipped. If they are not, the stored modules are converted to a linked list and stored after JDK8 if the list length reaches 8 Will convert the linked list to a red-black tree structure for storage but this approach is rarely triggered

An object’s storage index is calculated from its hash code value, and it can be found by performing a few comparisons between elements at the corresponding position in the hash table (table element).

The Set system saves, retrieves, deletes the object to have very high efficiency.

For objects to be stored in a Set, the corresponding class must override the equals() and hashCode(Object obj) methods to implement the Object equality rule

Common subinterfaces:

  • A HashSet does not store the order in which elements are saved

At the bottom layer, data is stored in the form of Hash tables, so the read efficiency is high. Data is directly read based on the Hash value

  • The underlying LinkedHashSet is a linked list that guarantees the order of entry but still cannot be repeated

Slightly less efficient when ordered and not repeated

The List interface

The elements in the collection class that implements the List interface are ordered and allow repetition.

Each element in the List corresponds to an integer serial number to record its position in the set. You can access the elements in the set according to the serial number.

The List collection classes provided by the JDK API are commonly used:

  • ArrayList
  • LinkedList

Common methods:

Public Object GET (int index) Returns the number of elements in the list

public Object add(int index, Object element); Inserts the specified element at the specified position in the list. Will be currently in that position

The element, if any, and all subsequent elements move to the right

public Object set(int index, Object element) ; Replaces the element at the specified position in the list with the specified element

Public Object Remove (int index) Removes the element at the specified position in the list

Public ListIterator ListIterator () returns a ListIterator for this list element

Remove (Object obj) If obj exists, remove it directly

Remove (int index) removes the element at the specified position and returns the element to the caller

ArrayList

A collection of lists implemented using array structures

Advantages:

  • It is efficient to extract elements using indexes
  • It uses indexes to quickly locate objects

Disadvantages:

  • The element is slow to delete or insert
  • Because we are using arrays, we need to move the following elements to adjust the index order,

LinkedList

LinkedList is a collection implemented using a two-way LinkedList. LinkedList has some new insert and delete methods.

Advantages:

  • High efficiency for frequent insert or delete elements
  • Suitable for implementing stacks and queues

Disadvantages:

Reading data can only be traversed in a certain direction, which is inefficient

Map

In a Collection, Map and Collection are a side-by-side relationship that internally stores key-value pairs. The key value cannot be duplicated and is unordered. Value is not required.

JDK API Map implementation classes are commonly used:

  • Internally, a HashMap uses a hash table to hash key-value mapping pairs.

1. The most frequently used set.

LinkedHashMap is a subclass of HashMap

1. Use a hash table to store mapping pairs

2. Use a linked list to record the insertion sequence of mapping pairs.

The key-value mapping pairs stored in the Map implementation class are uniquely identified by keys, and the underlying keys are stored by sets. Therefore, the classes that correspond to the “keys” of the mapping pairs stored in the Map must override the hashCode () and equals() methods. String is commonly used as the Map key.

Common Map interface methods:

Legacy class

Vector

The older version of ArrayList has most of the same operations as ArrayList except that Vector is thread synchronized.

It has an enumeration method that is similar to Iterator for traversal. ForEach and Enumcation can also be used to traverse collections.

Stack

• The Stack class, which is a subclass of Vector, is a LIFO Stack that stores elements. Thread synchronous.

The Stack class extends the Vector class by adding five methods

Hashtable

The older version of HashMap, created in JDK1.0, replaces Hashtable with HashMap in JDK2.0 and has thread synchronization capabilities of its own.

It is used in much the same way as HashMap.

Properties

A subclass of Hashtable that fetches information from the configuration file in the current project. This class has no generics and all key-values are strings

The Properties class represents a persistent set of Properties. Properties can be saved in or loaded from a stream. Each key and its corresponding value in the property set is a string.

The setProperty(String Key, String Value) method is not recommended for storing elements such as PUT and putAll, since key-value pairs are strings. GetProperty (String key) should be used for similar values.

Sorting interface

TreeSet & TreeMap

There is an auto-sorted storage set in the collection, and red-black trees are used for data storage underneath.

Any data stored in this collection is sorted by default

Wrapper classes for data types and strings implement a sort interface by default that sorts data in lexicographical order

If you want an element to be placed in a TreeSet or TreeMap, the object must implement a Comparable interface Comparable or it will throw an exception when stored

Comparable

The comparison interface, which should be implemented by all objects that need to implement collation, represents the class as a comparable class.

To implement Comparable, you need to implement its CompareTo(Object O) method

Rules for judging in ascending order:

A.age > b.age The value must be a positive integer

A.age < B.age The value must be a negative integer

A.age == B.age Returns 0

In descending order, you simply swap positive and negative integers

Advantage: Unordered set the sorting rules, in the sorting method can be directly sorted

Disadvantages: If Comparable is implemented in a project, the object can only be sorted in one way by default

Comparator

Compare (Object O1,Object O2). Compare (Object O1,Object O2)

The comparison rules are consistent with those in Comparable.

Advantages: Different comparators can be defined according to different requirements in a project, and precise comparison rules can be used to sort data according to specific requirements

Disadvantages: You need to manually tell the sorting interface the collation rules (set parameters) when you use them. If you use them only once, you will see anonymous inner classes or Lambda expressions

When an object implements the Comparable interface with a Comparable sort class, the Comparable implementation rules will be overridden if the Comparable class is shown calling the Comparator otherwise the default Comparable is used

Collections

The utility class specially designed for collections provides common functions of collections for developers to improve development efficiency.

Common methods:

Void sort(List List) Sorts the specified List in ascending order based on the natural order of the elements. List all elements in the List must implement the Comparable interface. Void shuffle(List List) Randomly arranges the elements in the List. Void reverse(List List) Inverts the elements in the List. Void copy(List dest, List SRC) copies elements from the SRC List to the dest List. List synchronizedList(List List) Returns a synchronous (thread-safe) List supported by the specified List

Thread-safety of collection classes

Most of the collection classes do not have thread-safety considerations by default, and programs must implement synchronization themselves to ensure that shared data can be accessed without error in multiple threads:

Using a Synchronous lock

Synchronized (list) {list. Add (…). ; }

Use the synchronizedXxx() method of java.uitl.collections to return a synchronized container object

• List List = Collections. SynchronizedList (new ArrayList ());

This approach is still modified with synchronized during iteration

Starting with JDK5.0, a concurrent package is provided, which provides objects that are useful for concurrent operations. Common objects associated with collections are:

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet

The above objects are balanced on synchronization and efficiency. They are only locked when elements are modified, but not locked when elements are read, which improves the read efficiency and is suitable for data with strong concurrency and short modification.

Well, this is the end of today’s article, I hope to help you confused in front of the screen