Interface and implementation separation
To hold a reference to a collection by using an interface type
Advantage:
- When you build a collection, you don't need to know which implementation to use
- When you change the implementation, you only need to change where the constructor is called.
If you need to implement your own collection classes, you can extend a set of classes that begin with abstract, extending these analogies to make all the methods in the interface much easier.
Interface
- Collection
Two basic methods
public interface Collection<E>{ boolean add(E element); Iterator<E> iterator(); ...}
- List
An ordered set, Access way: iterators and integer indexes
An ordered set of arrays can be accessed quickly and randomly, and the list of random accesses is slow, preferably using iterators to traverse
- Set
Set: Add method does not allow duplicate elements to be added
The Equals method of the set needs to ensure that two sets contain the same elements that are considered equal and do not require a sequence.
The Hashcode () method also ensures that two sets with the same elements get the same hash code.
- SortedSet
Provides a comparer object for sorting, and defines a method that can get a subset of the collection view
- SortedMap
Ditto.
- Navigableset
Contains methods for searching and traversing ordered sets and mappings.
- Navigablemap
Ditto.
Collection Frame diagram
Specific collection
In addition to the classes that end with map implement the collection interface, the class at the end of the map implements the map interface
| collection type |
description |
| arr Aylist |
dynamically growing and shrinking index sequence |
| linkedlist |
efficient insertion and deletion of ordered sequences at any location |
| Arraydeque |
Loop Array Implementation of the double-ended queue |
| HashSet |
no unordered collection of repeating elements |
| TreeSet |
ordered set |
| enumset |
contains a set of enum types |
| linkedhashset |
Remembering the set of element insertion Order |
| priorityqueue |
allows efficient deletion of a collection of minimum elements |
| HashMap |
data structure for storing key-value pairs |
| TreeMap |
key values in an ordered array of mappings |
| enummap |
key value is a mapping table of enum type |
| lindedhashmap |
Remember key-value Entry 8 Add Order Mapping table |
| weakhashmap |
A mapped table that is reclaimed after its value is not useful |
| identityhashmap |
map table with = = rather than equals to compare key values |
LinkedList
Linkedlist.add () Adds an element to the tail of the list.
The contains () method detects whether an element exists in the linked list.
Get (N) returns the nth element. Low efficiency is not recommended.
Search from tail end when index is greater than N/2
Listiterator interface
The location-dependent Add method is the responsibility of the iterator. Iterator sub-interface Listiterator contains the Add method and Prevous and hasprevious methods used to reverse-traverse the linked list.
The Add method relies on the position of the iterator. The Remove method relies on the state of the iterator and cannot call the Remove method multiple times.
Nextindex and Previousindex return the next call to next to return the integer index of the returned element, and the pre returns the next previous the integer index of the returned element, which is highly efficient because the iterator maintains the current position count value
ArrayList
Array list, implements dynamic redistribution of object dynamic array, realizes the list interface
In contrast to vectors, vector all methods are synchronous and can be multithreaded to secure access to a vector object, but if only one thread accesses it, the code needs to spend a lot of time on the synchronization operation. and ArrayList is not synchronous.
It is recommended that you do not need synchronization with ArrayList and use vectors when synchronizing
Hashtable
A hash table computes an integer, called a hash code (HASHCODE), for each object.
The hash list in Java is implemented with a list of linked lists, each of which is called a bucket, to find the position of the object in the table, the hash code is calculated first and the bucket count is the index of the bucket that holds the element.
A bucket that is full is called a hash conflict and requires that the new object be compared to all objects in the bucket to see if it already exists.
In Java Se8, when the bucket is full from a linked list to a balanced binary tree, the selection of the hash function improperly produces a lot of conflicts, or malicious code trying to fill the hash list with multiple values of the same hash code, which can improve performance.
Some people think that it is best to set the number of barrels to prime numbers, to prevent the accumulation of keys. The standard library uses a power of 2, the default value is 16, and the value provided for the table size is automatically converted to the power of the next 2.
Reload factor, default 0.75. The position in the table that exceeds the filling factor is filled in with the element and then hashed with the double bucket count.
TreeSet
A tree set is an ordered set that, when inserted in any order, is automatically rendered in sorted order.
Sorting is done using the tree structure, which is currently a red-black tree.
Adding elements to the tree is slower than adding to the hash table, but it is much faster than checking for duplicate arrays and linked lists. The tree contains n elements, and the inserted element will probably compare Log 2 n times.
Java SE 6 begins treeset implements the Navigabnleset interface to add positioning elements and reverse traversal methods
Arraydeque and LinkedList
- Implements a dual-ended queue Deque interface
Priorityqueue Priority Queue
- Insert them in any order and retrieve them in sorted order.
- Call remove always gets the smallest element of the current priority queue
- And no sort of
- Using the heap implementation, is self-tuning two fork tree, using Add and remove will automatically let the smallest element moved to the root
- Typical Use cases: task scheduling
Mapping
Workaround:
- Counts.put (Word,counts.getordefault (word,0) +1);
- Counts.putifabsent (word,0); Counts.put (Word,counts.get (word) +1);
- Counts.merge (word,1,integer::sum);
Map view
The collection framework does not consider a map to be a collection, but it can get a collection of key, value, and key-value pairs.
The set interface extends the collection interface so that it can be used like a collection keyset
- The keyset view call remove removes the key-value pair from the map
- Cannot add element to view, call add will throw unsupportedoperationexception error
Weak hash mapping
Weakhashmap: Because the mapping has been active, the garbage collector cannot reclaim values that have not been referenced, so it needs to be recycled by the program itself, so Weakhashmap is designed.
- When you save a hash key with a weak reference, the garbage collector finds that an object is referenced only by a weak reference and reclaims it and joins the weak reference to the queue. Weakhashmap Periodic check queue, once a weak reference to join the queue means that the key is no longer used by others and has been recycled, Then Weakhashmap Delete this entry.
Linked hash sets and mappings
Linkedhashset and Linkedhashmap remember the order in which element items are inserted.
- Link hash mappings iterate using the access order rather than the insertion order
- Calling get or put will be the item moving from the current position to the end of the list
- Affects only the position of the entry in the linked list, and the buckets in the hash table are not affected
- The least recently used principle that can implement cache
Enumeration sets and mappings
Enumset is an efficient implementation of enumeration type element sets
- Because enumeration types have only a limited number of instances, internal bit sequences are implemented
- Corresponding values in the set, corresponding to the position 1
- No public constructors, use static factory methods to construct
- Using the Set interface common methods to modify
Enummap is a mapping of the key type to an enumeration type, directly and efficiently using an array of values, and when used, specifies the type of the key in the constructor
Identifying Hash Mappings
Identityhashmap
- Calculate hash codes using System.identityhashcode
- Use = = When comparing objects, not equals
- Different key objects have the same contents as different objects
- Useful for implementing object traversal algorithms (such as Object serialization)
View and Wrapper
Algorithm
One of the great advantages of a generic collection interface is that the algorithm only needs to be implemented once.
Such as
public static <T extens Comparable> T Max (Collection<T> c){ ...}
You can use one method to calculate the list, the largest element in an array, or an array.
Sort and mix
Sorting in Java transfers all elements of the list to an array, then sorts the sorted sequence back into the list
The sorting algorithm used by the collection framework is a merge sort, slower than fast but stable, and does not need to exchange the same value object.
Two-point Search
- The Collections.binarysearch method achieves a two-point lookup
- Return negative I when not found, insert the value at position-i-1 to insert the value and keep it in order
- If you provide a list, it will automatically become a linear lookup
Simple algorithm
The collections class provides a copy of the list to another, a constant value to populate the container, an inverse list of the elements to sort, and get the maximum number of simple algorithms. Calling these methods is useful for code readability.
Batch Operations
- Batch deletion can get a subset from the view and call the Clear method
- Use the Retainall (Otherset) method to find the intersection
- RemoveAll (Otherset) method
Collection and Array conversions
Array to Collection
string [] values=...;HashSet<String> staff=new HashSet<>(Arrays.asList(values));
Get an array from a collection
object[] values=staff.toArray();
This gets an array of objects
The need to get a string array
string[] values = staff.toArray(new String[0]);
Write your own algorithm (set as parameter)
It is best to use interfaces rather than specific implementations
Legacy Collections
- Enumeration
- Attribute Mappings
- Stack
- Bit set Bitset
From for notes (Wiz)
Java Collection Framework