Review the Java Collection Framework.

xiaoxiao2021-03-06  112

The Java platform provides a new collection framework. The "Collection Framework" is mainly composed of a set of interfaces used to operate objects. Different interfaces describe a set of different data types.

Java 2 Collection Frame

Collection interface: 6 interfaces (short dashed lines) indicating that different collection types are the basis of the collection framework.

Abstract class: 5 abstract classes (long dashed lines), implementation of partial integration interfaces. Scalable to custom set classes.

Implementation class: 8 implementation classes (solid line representation), specific implementation of the interface.

To a large extent, once you understand the interface, you understand the framework. Although you always create interface-specific implementations, access to the actual collection should limit the use of the interface method; therefore, allow you to change the basic data structure without having to change the other code.

· The Collection interface is a group of allowed repetitive objects.

• The SET interface inherits the Collection, but does not allow repeated, using one of its interiors.

· The List interface inherits the Collection, allows you to repeat, place the element to place the element, and will not rearrange it.

• The MAP interface is a key-value object that is held, that is, the HEY-VALUE PAIRS. There is no repetition in MAP. Have your own internal arrangement mechanism.

• The element type in the container is Object. When an element is obtained from a container, it must be converted into the original type.

Java 2 Simplified Collection Frame

Collection interface 1.collection interface

Used to represent any object or element group. Use this interface when you want to handle a set of elements as much as possible.

(1) Single element added, delete operation:

Boolean Add (Object O): Add object to a collection

Boolean Remove (Object O): Delete the object O if there is an object with the O, if there is an object with the O

(2) Query operation:

INT size (): Returns the number of elements in the current collection

Boolean isempty (): Is there any elements in the collection

Boolean Contains (Object O): Whether to find a collection of objects O

ITerator iterator (): Returns an iterator to access the individual elements in the collection

(3) Group operation: acting on element group or whole collection

Boolean ContainSall (Collection C): Find all elements in the collection C

Boolean Add (Collection C): Add all elements in the collection C to the collection

Void clear (): Delete all elements in the collection

Void Removeall (Collection C): Remove all elements in the collection C from the collection

Void RetainAll (Collection C): Remove the elements that do not contain in the collection C

(4) Collection converts to the Object array:

Object [] toarray (): Returns an Array with a collection of all elements

Object [] toArray (Object [] a): Returns an Array containing all elements of the set. The model returned by the runtime is the same, and the parameter A needs to be converted to the correct type.

In addition, you can convert a collection into any other object array. However, you cannot directly convert the collection into an array of basic data types because the collection must hold objects.

"Body interface method is optional. Because an interface implementation must implement all interface methods, the calling program requires a way to know that an optional method is not supported. If a option is called, a unsupportedOperationException It is thrown, the operation failed because the method is not supported. This exception class inherits the RuntimeException class to avoid putting all set operations into the try-catch block. "Collection does not provide a GET () method. If you want to traverse the elements in Collectin, you must use item.

1.1.AbstractCollection abstraction

The AbstractCollection class provides the basic functionality of the specific "Collection Framework" class. Although you can implement all methods of the Collection interface, other methods are implemented by the AbstractCollection class in addition to the Iterator () and Size () methods implementation in the appropriate subclass. If the subclass is not overwritable, the options such as add () will throw an exception.

1.2.iterator interface

The Iterator () method of the Collection interface returns an Iterator. The Iterator interface method can access the individual elements in the collection one by one by one, and securely remove the appropriate elements from the Collection.

(1) Boolean Hasnext (): Judging whether there is another accessible element

Object next (): Returns the next element to be accessed. If the end of the collection is reached, the NosuchelementException is thrown.

(2) Void remove (): Delete the object returned last time. This method must be followed after access to an element. If the collection has been modified last time, the method will throw an IllegalStateException.

"Deleting operations in iTerator also have an impact on the underlying Collection."

The iterator is fault-fast. This means that when another thread modifies the underlying collection, if you are using the Iterator traversal collection, Iterator will throw ConcurrentModificationException (another RuntimeException exception) exception and immediately failed.

2.List interface

The LIST interface inherits the Collection interface to define an ordered collection that allows the repetition. This interface can not only process a part of the list, but also add a positional operation.

(1) The facing operation includes the function of inserting an element or collection, further comprising the function of acquiring, removing or changing elements. Searching elements in list can start from the head or tail of the list, if an element is found, the location of the elements are also reported:

Void Add (INT INDEX, Object Element): Add an element ELEMENT on the specified location INDEX

Boolean Addall (INDEX, Collection C): Add all elements of the collection C to the specified location Index

Object get (int index): Returns the element of the specified location in the list

INT INDEXOF (Object O): Returns the position of the first element O, otherwise returns -1

INT LastIndexof (Object O): Returns the location of the last element O, otherwise returns -1

Object Remove (int index): Delete elements on the specified location

Object Set (int index, object element): replaces the elements on Index with element Element and return old elements

(2) The List interface is not only used by the entire list, but also handles the subset of the collection:

Listiterator ListIterator (): Returns a list iterator to access the elements in the list

Listiterator ListIterator (int index): Returns a list iterator to start accessing the elements in the list from the specified location index

List Sublist (int fromindex, int toindex): Returns a list view from the specified location fromNDEX (included) to the toIndex (not included)

"Changes to sub-lists (such as add (), remove (), and set () calls also have an effect on the underlying List."

2.1.Listiterator interface

The ListIterator interface inherits the Iterator interface to support the elements in the underlying collection, and support two-way access. Listiterator does not have a current location, between the cursor is between the values ​​returned by the previous and next method. A list of a length N, N 1 effective index value:

(1) Void Add (Object O): Add the object o to the current location

Void Set (Object O): Use the object O to replace the previous element accessed by the next or Previous method. If the list structure is modified last time, ILLEGALSTATEEXCEPTION will throw an unlegation.

(2) Boolean Hasprevious (): During the judgment, there is an element to be accessed when it is iterated.

Object previous (): Return to the previous object

INT nextIndex (): Returns the index of the elements that will be returned next time

INT PreviousIndex (): Returns the index of the elements that will be returned next time

"Under normal circumstances, do not use Listiterator to change the direction of the collection element - forward or back. Although it can be implemented in technology, next () immediately calls next (), returning the same element. Put the called next () And previous ()'s order reversed, the same result. "

"We also need to explain the add () operation slightly. Adding an element can cause the new element to be added to the front of the implicit cursor. Therefore, call previous () after adding an element will return new elements, and call next () Inseparable, return the next element before adding operations. "

2.2.AbstractList and AbstractSequentialList abstraction

There are two abstract List implementations: AbstractList and AbstractSequentialList. Like the AbstractSet class, they cover the equals () and havehcode () methods to ensure that the two equally collections return to the same hash code. These two lists are equal if the two lists are equal and contain the same elements as the same order. The HashCode () implementation here is specified in the List interface definition, but implemented here.

In addition to equals () and havehcode (), AbstractList and AbstractSequentialList are part of the rest of the List method. Because the random access and order access of the data is implemented separately, the creation of a specific list implementation is easier. A set of methods that need to be defined depends on the behavior you want to support. You will never have to provide yourself is the implementation of the Iterator method.

2.3. LinkedList class and arraylist class

There are two conventional List implementations in the Collection Framework: ArrayList and LinkedList. Which of the use of two LIST depends on your specific needs. If you want to support random access, you don't have to insert or remove elements anywhere in the end of the end, then ArrayList provides an optional collection. However, if you want to add and remove elements from the middle of the list, as long as the order of access list elements, the LinkedList is better. "ArrayList and LinkedList have implemented clONEABLE interfaces, all of which provide two constructor, one no-argument, one accept another collection"

2.3.1. LinkedList class

The LinkedList class adds some methods of processing two end elements.

(1) Void AddFirst (Object O): Add the object o to the beginning of the list

Void AddLast (Object O): Add the object o to the end of the list

(2) Object getFirst (): Return to the element starting

Object getlast (): Returns the elements ending at the list

(3) Object removefirst (): Delete and return the elements starting at the list

Object removelast (): Delete and return the elements ending the list

(4) LinkedList (): Build a list of empty links

LinkedList (Collection C): Build a list of linked lists and add all elements of the collection C

"Use these new methods, you can easily treat LinkedList as a stack, queue, or other-oriented data structure."

2.3.2. ArrayList class

The ArrayList class encapsulates a dynamic redistributed Object [] array. Each ArrayList object has a Capacity. This Capacity indicates the capacity of the array of elements in the store. When the element is added to arraylist, its Capacity is automatically increased within a constant time.

In a program that adds a large number of elements to an ArrayList object, you can add Capacity using the EnSureCapacity method. This reduces the increase of the number of redistributions.

(1) Void EnSureCapacity: Adds ArrayList object capacity to MINCAPACITY

(2) Void Trimtosize (): Solving the ArrayList object capacity is the current size of the list. The program can use this operation to reduce ArrayList object storage space.

2.3.2.1. Randomaccess interface

A feature interface. This interface does not have any methods, but you can use this interface to test whether a collection supports valid random access. ArrayList and VECTOR class are used to implement the interface.

3.SET interface

The SET interface inherits the Collection interface, and it does not allow a replica in the collection, and each particular SET implements the equivalent of the class-dependent Equals () method to check the uniqueness. The SET interface does not introduce a new method, so set is a collection, but its behavior is different.

3.1. Hash table

The Hash table is a data structure for finding an object. The Hash table calculates an integer for each object, called the Hash Code (Hash code). The Hash table is an array of a link list. Each list is called a buckets (hash). Calculation of object position Index = hashcode% buckets (hashcode is the object hash code, BUCKETS is the total number of hash tables).

When you add an element, sometimes you will encounter a hash dollar that has already filled the element, which is called Hash Collisions. At this time, you must determine if the element has already exist in the hash table.

If the hash code is reasonably randomly distributed, and the number of hash tables is large enough, then the number of hash conflicts will decrease. At the same time, you can also better control the running of the hash table by setting an initial number of hash tables. The number of initial hash tables is buckets = size * 150% 1 (size is the number of expected elements). If the elements in the hash table are too full, it must be rehashing (another hash). Then, the hash of the hash of the hash, and retransmit the original object into the new hash table, and the original hash table is deleted. The Load Factor decides when to have a hash of the hash table. In the Java programming language, the load factor default is 0.75, and the default hash table is 101.

3.2. Comparable interface and Comparator interface

There are two comparison interfaces in the Collection Framework: Comparable interface and Comparator interface. Java build classes such as String and Integer implements the Comparable interface to provide certain sorting methods, but this can only be implemented once. For classes that do not implement the COMPARABLE interface, or custom classes, you can define your own comparison by the Comparator interface.

3.2.1. Comparable interface

In the java.lang package, the Comparable interface is suitable for a class with natural sequence. Assuming that the object collection is the same type, which allows you to sort a collection into natural sequence.

(1) INT COMPARETO (Object O): Compare the current instance object with the object O, returns a negative value before located in the object O, if the two objects are the same in the sort, then return 0, if located behind the object O, return Positive value

Twenty-four classes in Java 2 SDK implementation Comparable interface. The following table shows the natural sort of eight basic types. Although some categories share the same natural sorting, only the class is more than one class.

Class Sort BigDecimal, Biginteger, Byte, Double, Float, Integer, Long, Short Press Digital Sort CHARACTER Sorting Sort by Unicode Value Sword Sort by Character Unicode Value in String

Create your own sort order using the Comparable interface, just implement the compareto () method. Usually, depending on natural sorting of several data members. At the same time, class should also override Equals () and havehcode () to ensure that two equal objects return to the same hash code.

3.2.2. Comparator interface

If a class cannot be used to implement java.lang.comparable, or you don't like the default Comparable behavior and want to provide your own sort order (possibly multiple sorting methods), you can implement a comparator interface to define a comparator.

(1) INT COMPARE (Object O1, Object O2): Compare two objects O1 and O2, if O1 is located in front of O2, return negative, if it is considered to be the same in the sort order, return 0 If O1 is behind O2, return positive value.

"Similar to Comparable, 0 return value does not represent elements equal. One 0 return value just means that two objects are ranked in the same location. How to deal with the COMPARATOR user. If the result of two unequal elements is zero, you should first Confident that that is the result you want, then record behavior. "

(2) Boolean Equals (Object Obj): Indicates whether the object OBJ is equal to the comparator.

"This method overwriters the equals () method of Object (), checks the same identity of Comparator implementation, not in a comparison state."

3.3. Sortedset interface

"Collection Framework" provides a special SET interface: sortedset, which keeps the elements' ordered order. The SortedSet interface is set to the view (subset) and its both ends (ie, head and tail) provide an access method. Change the view will reflect the source set when you process the subset of the list. In addition, the change source set is also reflected in the subset. This happens that the view is specified by the elements of the two ends instead of the subscript element, so if you want a special high-end element (TOEELEMENT) in subset, you must find the next element. Adding an element that is added to the sortedset implementation class must implement the Comparable interface, otherwise you must provide a constructor to provide a COMPARATOR interface implementation. The Treeset class is its only implementation.

"Because the set must contain unique items, if the two elements compare the two elements cause 0 return values ​​(by comparable COMPARETO () method or Compare () method), the new element is not added. If two Elements are equal, it is ok. But if they are not equal, you should modify the comparison method, let the comparison method and equals () are consistent. "

(1) Comparator Comparator (): Returns the comparator used when sorting the element, returns NULL if the CompareTo () method of the Comparable interface is compared

(2) Object first (): Return the first (minimum) element in an ordered collection

(3) Object last (): Return the last (highest) element in an ordered collection

(4) Sorted Subset (Object Fromelement): Returns the sortedset view (subset) (subset) (subset) (subset) (subset) (subset) (subset) (subset) (subset) (subset) (subset) (subset) (subset)

(5) SortedSet headset: Returns a view of the sortedset, each element is less than TOEEEMENT

(6) SortedSet Tailset: Returns a view of the sortedset, each element is greater than or equal to FromenElement

3.4. AbstractSet Abstract Class

The AbstractSet class covers the Object class equals () and hashcode () methods to ensure that the two equal sets return the same hash code. These two sets, etc. if the two sets are equal and including the same elements. According to the definition, the hash code is the sum of the concentrated element hash code. Therefore, regardless of the intended internal order, two equal gatherings have the same hash code.

3.4.1. Object class

(1) Boolean Equals (Object Obj): Compare two objects to determine if they are the same

(2) Int hashcode (): Returns the hash code of the object. The same object must return the same hash code

3.5. Hashset class and Treeset class

"Collection Framework" supports two common implementations of the SET interface: Hashset and Treeset (TreeSet implementation SortedSet). In more cases, you will use the Hashset to store a collection of repeating freedom. Taking into account the efficiency, the object added to the Hashset needs to implement the HashCode () method in a way that is properly assigned a hash code. Although most system classes cover the default HashCode () and Equals () implementations in Object, don't forget to overwrite HashCode () and Equals () when you create a class that you want to add to the Hashset.

The TreeSet implementation is useful when you want to insert and extract elements in an orderly manner from a collection. In order to be smooth, the elements added to the Treeset must be sorted.

3.5.1.hashset class

(1) Hashset (): Build an empty hash set (2) Hashset: Build a hash set and add all elements in the collection C

(3) Hashset (int initialcapacity): Build an empty haveh collection with specific capacity

(4) Hashset (int initialcapacity, float loadfactor): Build a holiday set with specific capacity and load factors. LoadFactor is a number between 0.0 to 1.0

3.5.2. Treeset class

(1) Treset (): Build an empty tree set

(2) Treeset: Build a tree set and add all elements in the collection C.

(3) Treeset: Build a tree set and sort the elements using a specific comparator

"The Comparator comparator does not have any data, it is just a memory of the method. This object is sometimes referred to as a function object. Function objects are typically defined as an instance of an anonymous internal class in the" running process "."

Treeset: Build a tree set, add all elements in an ordered set S, and use the same comparator as the ordered set S

3.6. LinkedHashSet class

LinkedHashSet extension hashset. LINKEDHSHSET implementation will help if you want to track the order of the elements added to havehset. The iterator of the Linkedhashset access each element is accessed according to the insertion order of the element. It provides an ordered collection that can quickly access individual elements. At the same time, it also increases the cost of implementation, because each element in the hash table is linked to a double link list.

(1) LinkedHashSet (): Build an empty link hash

(2) LinkedHashSet: Build a link hash set and add all elements in the collection C.

(3) LinkedHashSet (int initialcapacity): Build an empty link with a specific capacity has a hash set

(4) LinkedHashSet (Int InitialCapacity, Float LoadFactor): Build an empty chain terminal with a specific capacity and load factor. LoadFactor is a number between 0.0 to 1.0

"To optimize the use of Hashset space, you can tune the initial capacity and load factor .treeset does not contain tuning options because the tree is always balanced."

4. MAP interface

The MAP interface is not inheritance of the Collection interface. The MAP interface is used for maintenance key / value pairs (Key / Value PAIRS). This interface describes the mapping from the non-repeated key to the value.

(1) Add, delete the operation:

Object Put (Object Key, Object Value): Place a keyword associated with each other with a value in the image. If the keyword already exists, the new value related to this keyword will replace the old value. Method Returns the old value of the keyword, returns NULL if the keyword does not exist

Object Remove (Object Key): Remove from the image with key-related mapping

Void Putall (MAP T): Add all elements from a particular image to this image

Void Clear (): Remove all mappings from the image

"The keys and values ​​can be null. However, you cannot add MAP as a key or value to itself."

(2) Query operation:

Object GET (Object Key): Get values ​​associated with the keyword key and returns objects related to keyword key, return NULL if you do not find this key in this image.

Boolean ContainsKey: Decluders if there is a keyword key

Boolean ContainSValue (Object Value): Determines if there is a value Value in the image

INT size (): Returns the number of maps in the current image

Boolean iSempty (): Decision whether there is any mapping (3) view operation in the image: Processing Image Middle Key / Value Group

Set KeySet (): Back to the image of all keywords in the image

"Because the collection of miles must be unique, you can use set support. You can also remove elements from the view, and the keywords and its related values ​​are deleted from the source image, but you can't add any elements. "

Collection Values ​​(): Returns the view set of all values ​​in the image

"Because the collection of maps is not unique, you can use Collection. You can also remove elements from the view, and the values ​​and its keywords are deleted from the source image, but you can't add any elements."

Set entryset (): Returns the view set of map.Entry objects, namely the keyword / value pair in the image

"Because mapping is unique, you can use set support. You can also remove elements from the view, while these elements are deleted from the source image, but you can't add any elements."

4.1. Map.Entry interface

Map's entryset () method returns an object collection that implements the map.Entry interface. Each object in the collection is a specific key / value pair in the underlying Map.

Through this collection iterator, you can get the keys or values ​​of each entry (unique acquisition mode) and make changes. When the entry returns through the iterator, unless it is a setValue () method returned by the iterator itself, the remaining MAP external modifications will cause this set to be invalid, while generating entry behavior Not defined.

(1) Object getKey (): Returns the keywords for the entry

(2) Object getValue (): Returns the value of the entries

(3) Object setValue (Object value): change the value in the related image to Value and return the old value

4.2. SortedMap interface

"Collection Framework" provides a special MAP interface: sortedMap, which is used to hold the orderly order of the keys.

The SortedMap interface is a view (subset) of the image, including two endpoints provide an access method. In addition to the sorting is the key acting on the mapping, SortedMap is processed, and the SortedSet is processed.

Adding an element added to the sortedMap implementation class must implement the Comparable interface, otherwise you must provide a constructor to provide a COMPARATOR interface implementation. The TreeMap class is the only implementation thereof.

"Because for mapping, each key can only correspond to one value, if two keys generate 0 return values ​​(by comparable compareto () method if two keys are compared when the button / value pair is added to the Compare () method through Compare () method So, the original key is replaced by the new value. If the two elements are equal, that is, it is ok. But if you don't wait, then you should modify the comparison method, let the comparison method and equals () are consistent. "

(1) Comparator Comparator (): Returns the comparator used when sorting the keyword, returns NULL if the keyword is compared using the CompareTo () method of the Comparable interface.

(2) Object firstkey (): Returns the first (minimum) keyword in the image

(3) Object lastkey (): Returns the last (highest) keyword in the image

(4) SortedMap Submap (Object fromkey, Object Tokey): Returns sortedMap view from fromKey to ToKey (not included) (subset)

(5) SortedMap Headmap: Returns a view of SortedMap, and the keys of each element are smaller than Tokey

(6) SortedSet Tailmap (Object fromkey): Returns a view of SortedMap, which is greater than or equal to fromkey4.3. AbstractMap abstract class

Similar to other abstract sets, the AbstractMap class covers the equals () and havehcode () methods to ensure that two phase-like mappings return the same hash code. If the two mappings are equal, the same key is included and each key has the same value in these two mappings, and the two mappings are equal. The mapping hash code is the sum of the map element hash code, each of which is an implementation of the map.Entry interface. Therefore, regardless of how the internal order is mapped, two equal mappings report the same hash code.

4.4. HashMap class and Treemap class

"Collection Framework" offers two conventional MAP implementations: HashMap and Treemap (Treemap implementation SortedMap interface). Insert, delete, and locate elements in Map, HashMap is the best choice. But if you want to traverse keys in natural order or custom order, TreeMap is better. The key class that is added using HashMap requires explicitly defines the implementation of HashCode () and Equals ().

This TreeMap has no tuning options because the tree is always equilibrium.

4.4.1. Hashmap class

To optimize the use of HashMap space, you can tune the initial capacity and load factors.

(1) HashMap (): Build an empty hash image

(2) HashMap (MAP M): Build a hash image and add all mappings of image M

(3) Hashmap (int initialcapacity): Build an empty hash image with a specific capacity

(4) Hashmap (int initialcapacity, float loadfactor): Build an empty hash image with specific capacity and loading factors

4.4.2. TreeMap class

TreeMap has no tuning option because the tree is always equilibrium.

(1) TreeMap (): Build an empty image tree

(2) TreeMap (Map M): Build an image tree and add all the elements in the image m

(3) TreeMap: Build an image tree and sort the keyword using a specific comparator

(4) TreeMap (SortedMap S): Build an image tree, add all mappings in the image tree S, and use the same comparator as the ordered image S

4.5. LinkedHashMap class

LINKEDHASHMAP Extended HashMap, insert the keyword / value to add a link hash image in the order. Like LinkedHashSet, LinkedHashMap is also used in a dual link list.

(1) LinkedHashMap (): Build an empty link hash image

(2) LinkedHashMap (MAP M): Build a link hash image and add all mappings in the image m

(3) LinkedHashMap (int initialcapacity): Build a empty link hash image with a specific capacity

(4) LinkedHashmap (int initialcapacity, float loadfactor): Build an empty link hash image with specific capacity and loading factors

(5) LinkedHashmap (int initialcapacity, float loadfactor,

Boolean AccessOrder: Build an empty link hash image with specific capacity, loading factors, and access order

"If you set AccessOrder to True, the link hash image will use access order instead of insertion order.

Alternative to each image. Each time you call the GET or PUT method, the relevant mapping is deleted from its current location, then place it at the end of the link image list (only the location in the list of link images will be affected, hash table Not affected. The hash table map always stays in the hash of the hash code corresponding to the keyword. "This feature is useful for the principle of" deleting the most recently used "in cache. For example, you can save the most commonly accessed mapping in memory and read objects that are not accessed frequently from the database. When you can't find a map in the table, and the mapping in the table has already been very full, you can let the iterator enters the table, and remove the beginning of the beginning of the enumeration. These are the most recently used mappings. "

(6) Protected Boolean Removeeldestentry: If you want to delete the oldest mapping, you can override this method to return True. This method is adjusted after a mapping has been added to the image. Its default implementation method returns false, indicating that the old mapping under the default condition is not deleted. But you can redefine this method so that you can choose a certain condition in the oldest mapping, or the image exceeds a certain size, returns True.

4.6. WeakhashMap class

WeakhashMap is a special implementation of MAP, which uses WeakReference (weak reference) to store the hash table keyword. When using this way, when the mapping key is no longer referenced outside WeakHashMap, the garbage collector will reclaim it, but it will incorporate weak references to the object into a queue. Weakhashmap runs regularly checks the queue to find new weakened applications. When a weak reference arrives at the queue, it means that the keyword is no longer used by anyone, and it has been collected. Then WeakhashMap deletes the relevant mapping.

(1) WeakhashMap (): Build an spaceless hash image

(2) WeakhashMap (MAP T): Build a weak hash image and add all mappings in the image T

(3) WeakhashMap (int initialcapacity): Build an empty weaker brightening with specific capacity

(4) WeakhashMap (INT InitialCapacity, Float LoadFactor): Build an empty weak haveh image with a specific capacity and load factor

4.6. Identityhashmap class

Identityhashmap is also a special implementation of MAP. In this class, the hash code of the keyword should not be calculated by the HashCode () method, but should be calculated by the System.Identityhashcode method (even if the HashCode method has been redefined). This is the method used by Object.hashcode to calculate the hash code based on the memory address of the object. In addition, in order to compare individual objects, IdentityHashMap will use ==, without using the equals method.

In other words, different keyword objects are also considered different objects even if their content is the same. The IdentityHashMap class can be used to implement Topology-PreserVing Object Graph Transformations (such as serialization or depth copy of objects), when converting, requires a "node table" to track those objects that have been processed. Quote. Even if there is an object equal, "node table" should not be seen. Another application is to maintain a proxy object. For example, debugging tools want to maintain a proxy object of each object during program debugging.

"The IdentityHashMap class is not a general significance! It implements intentional violations of the MAP interface requires comparison of objects through the Equals method. This class is only used in rare happening.

(1) IdentityHashMap (): Build an empty whole hash image, the default expected maximum size is 21 "Expected maximum size is the maximum number of key / value mappings that are expected to hold" "

(2) IdentityHashMap (MAP M): Build a whole hash image and add all mappings in the image m

(3) IdentityHashmap (int expectedmaxsize): Build an empty whole hash image with expected maximum size. When you place a key / value mapping of the expected maximum size, it will cause growth in the internal data structure, sometimes it is time to time.

转载请注明原文地址:https://www.9cbs.com/read-102038.html

New Post(0)