Java Note-collection interface for Java Note-collection

preface

In Java, the most common data interface is collection, and the most frequently asked questions in the interview are also questions related to collection. Based on my own interview experience, I made a simple arrangement, hoping to help my friends.

The Map interface for collections can be found in my blog: Java Notes for Sources – Map Interface for collections

The body of the

A collection of

A collection ofThere are two interfaces:CollectionandMap

The Collection interface

The Collection interface has three subinterfaces:

  • List: Ordered and elements are repeatable
  • Set: Unordered union elements are not repeatable
  • Queue: A first-in, first-out linear data structure in which only the first element of the Queue is observed.

The List interface

Common implementation classes for List are:

  • ArrayList: The underlying implementation is through arrays, high query performance, slow insert and delete. The advantage of its traversal lies in its continuity in memory.
  • LinkedList: Through bidirectional linked list implementation, query performance is slightly lower, but insert and delete performance is high, except implementationListInterface, but also implementedQueueInterface.
  • Vector: Data structure andArrayListSimilarly, throughsynchronizedTo achieve thread safety, andStackThe stack is implementedVectorOf the interface.

Key points:

1. A thread-safe way to implement ArrayList

  • usesynchronizedOr the lock
  • Direct use ofVector, but JDK1.2 is officially recommended to deprecate
  • useCollections.synchronizedList(list)To implement the

2. Construction and expansion of ArrayList

  • ArrayList arrayList =new ArrayList(), default generates an array of capacity 0, onlyadd()Element, the default initial capacity of 10 is allocated.
  • If all 10 capacities are full, the capacity is increased by 50% to 15.

Therefore, when accessing an array of known size, the initial capacity should be set as far as possible to avoid triggering continuous expansion operations.

3. Why does ArrayList insert and delete perform poorly? Insert and delete both involve copying arrays (i.e. data migration), and the earlier the operation, the longer the array that needs to be copied.

Why was Vector deprecated? The use of synchronized in all Vector methods greatly affects the performance of the entire data operation. In fact, Hashtable has a similar problem. So ArrayList became a Vector replacement after jdk1.2.

The Set interface

Common implementation classes for Set are:

  • HashSet: it is based onHashMapThe default constructor implemented is to build an initial capacity of 16 with a load factor of 0.75HashMap. Through rewritingequals(Object obj)Methods andhashCode()To achieve de-weighting.
  • TreeSet: The data structure is a red-black tree, which is de-weighted by a comparator. It is ordered in the sense that it is sorted by comparator elements.
  • LinkedHashSet:LinkedHashSetThe underlying useLinkedHashMapTo save all the elements, by rewritingequals(Object obj)Methods andhashCode()To achieve de-weighting. Its orderliness means that the order of storage is the same as the order of retrieval.

The Queue interface

There are three main implementation classes for Queue:

  • Non-blocking implementation classes, such as:ConcurrentLinkedQueue, the use ofCASThe operation implements an unbounded thread-safe queue, avoiding the performance impact of locking.
  • Blocking implementation classes, such as:ArrayBlockingQueue(bounded),LinkedBlockingQueue(unbounded), which blocks when the queue is full and new elements are added to the thread, stopping the addition and waiting for the queue to be empty.
  • deque:DueueElements can be added and removed at both ends.

Blocking queues implement blocking synchronization in a simple way, using the condition blocking control of a LOCK lock.

Common methods of Queue:

  • Add () : Adds a new element to the end of the queue.
  • offer(): Added an element at the end of the queue, returned when it was fullfalse.
  • Remove () : deletes the first element of the queue, and the element is a null-throw exception.
  • poll(): Deletes the first element of the queue, and returns if the element is emptynullIf it is not empty, the element is obtained.
  • Element () : Queries the first element of the queue, with a null-cast exception.
  • peek(): Queries the first element of the queuenull.

ConcurrentLinkedQueue

ConcurrentLinkedQueue is a thread-safe queue for atomic operations provided under java.util.Concurrent. Both ConcurrentLinkedQueue and LinkedBlockingQueue are thread-safe, the difference being:

  • LinkedBlockingQueue: Mostly used for task queues where a consumer consumes different messages from different producers.
  • ConcurrentLinkedQueue: Used mostly for message queues where a producer provides the same message to different consumers.

ArrayBlockingQueue

ArrayBlockingQueue Specifies the bounded blocking queue that the thread pool configures.

  • ArrayListNot good for queues, but arrays are good for queues,ArrayBlockingQueueIs a ring queue, which is a fixed-length, thread-safe blocking queue, internally implemented with a fixed-length array. It is thread safe and obstructive both throughReentrantLockTo achieve.
  • ArrayBlockingQueueThe process of dequeuing and enqueuing can be abstractly regarded as a vernier caliper of fixed length in memory. So when an exit occurs, the team leader is constantly changing, not alwaysitems[0], the first time is 0, and the second exit is 1, so there is no operation involving data migration.
    private final E[] items;// The underlying data structure
    private int takeIndex;// Index used for the next take/poll/remove
    private int putIndex;// Index used for the next put/offer/add
    private int count;// The number of elements in the queue

    /** Main lock guarding all access */
    private final ReentrantLock lock;/ / lock
    /** Condition for waiting takes */
    private final Condition notEmpty;// Wait for the conditions to exit the queue
    /** Condition for waiting puts */
    private final Condition notFull;// Waiting for the conditions to join the team
Copy the code

other

1. The difference between collections and arrays

  • An array has a fixed size and can only store data of the same data type
  • Collection features: The size can be dynamically expanded, can store various types of data

Conversions between collections and arrays

//array converts to list
int[] arr = {1.3.4.6.6};
List list =Arrays.asList(arr);

//list is converted to Array
String arratb[] =(String [])list.toArray();
Copy the code

2. Types of collections

  • Common set: usually has the highest performance, but does not guarantee the safety of multi-threading and concurrent reliability, for exampleArrayList.
  • Thread-safe collection: simply adds to the collectionsynchronizedSynchronous locking, which severely compromises performance, is even less efficient for concurrency, e.gHashTable.
  • Concurrent collectionsThe complex strategy not only ensures the safety of multithreading but also improves the efficiency of concurrency, such asConcurrentLinkedQueue.

3. Collections, the Collection utility class provided by Java

Collections is a Java utility class for Collections of sets, lists, and maps that provides a number of methods for sorting, querying, and modifying Collections:

  • Collections.sort(list) : Sort a collection by using a field in the collection:
  • Collections.shuffle(list) : random sorting of Collections:
  • Collections.binarysearch (list, “O”) : Finds elements in the specified collection, returning the index of the elements searched
  • Collections.max(list)/ collections.min (list) : Max/min
  • The Collections. IndexOfSubList (list, subList)/Collections. LastindexOfSubList (list, subList) : first appeared/the last time the index of the element
  • The Collections. ReplaceAll (list, “a”, “b”): Replaces the batched element with an element, just returned if the value to be replaced existstrue, otherwise returnfalse
  • Collections.reverse(list) : Reverses the order of the elements in the collection

Collections provides methods such as synchronization control over collection objects:

  • Collections.synchronizedCollection(collection): For implementationcollectionA collection of interface objects provides thread synchronization control
  • Collections.synchronizedList(list): For implementationlistA collection of interface objects provides thread synchronization control
  • Collections.synchronizedSet(set): For implementationsetA collection of interface objects provides thread synchronization control
  • Collections.synchronizedMap(map): For implementationmapA collection of interface objects provides thread synchronization control

4. Streaming expressions

Stream is the key abstraction for dealing with collections in Java8. It can specify what you want to do with collections, and can perform very complex operations like finding, filtering, and mapping data.

Stream features:

  • Not storing data: array or collection based creationstream.streamData is not stored specifically.
  • Do not change the original data:streamThe array and collection that created it will not be affected by the operation ofstreamThe aggregate, consume, or collect operation (terminate operation) of the
  • Delay the:StreamThe delayed execution nature means that it is allowed to modify the data source before the aggregation operation is performed, but not once the aggregation operation has begun.

Aggregation operations

Aggregate operations are similar to SQL statements, such as filter, map, reduce, find, match, sorted, and so on:

In the middle of operation

The intermediate operation returns a Stream object.

Screening and slicing:

  • Filter: Filters certain elements in the stream
  • Limit (n) : Gets n elements
  • skip(n): Skips the n element and matcheslimit(n)Achievable paging
  • distinct(): passes elements in the streamhashCode()equals()Removing duplicate elements

mapping

  • Map () : Takes as an argument a function that is applied to each element and maps it to a new element.
  • FlatMap () : Takes a function as an argument, replaces each value in the stream with another stream, and joins all streams into a single stream.

The sorting

  • Sorted () : Generates a new stream, sorted in natural order.
  • Sorted (Comparator comp) : Produces a new stream that is sorted by Comparator order

Termination of operations

The return value of the termination operation is no longer a Stream object than that of the intermediate operation, so it is called the termination operation and can fetch the corresponding value. One is that the Stream object can only terminate once.

Find and match

  • AllMatch (Predicate P) : Checks whether all elements match
  • FindAny () : Returns any element in the current stream
  • Max (Comparator c) : Returns the maximum value in the stream
  • ForEach (Consumer C) : iterator

reduction

  • Reduce (T iden,BinaryOperator b) : Can combine elements ina stream repeatedly to obtain a value.
  • reduce(BinaryOperator b): You can combine elements in a stream repeatedly to get a value. returnOptional.

collect

  • collect(Collector c): Converts the stream to another form. To receive aCollectorAn implementation of the interface used to giveStreamElements in the