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 Graph Collection Interface: 6 interfaces (short dashed lines), indicating that different collection types are the foundation 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 is 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 Add, Delete Action: Boolean Add (Object O): Add object to a collection Boolean Remove (Object O): Remove Object O (2) Query If you have objects with O, delete objects O (2) query operations: INT size (): Returns the number of elements in the current collection (): Is there any element Boolean ContainS (Object O) in the judgment collection: Find a collection of objects o Iterator item (): Return an iterator, used Access to each element (3) group operation: acting on the element group or the entire collection Boolean ContainSall (Collection C): Find whether all elements Boolean Addall (Collection C) in the collection C: Add all elements in the collection C Give the collection void Clear (): Delete all Elements Void Removeall (Collection C) in the collection: Remove all Elements in Collection C: Remove the elements that are not included in the collection C from the collection (4 ) Collection converts to Object arrays: object [] toarray (): Returns an Array Object [] Toarray (Object [] A) containing all elements of the collection: 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 Abstract class AbstractCollection class provides the basic features 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 item () 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." 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.
The 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 from the list can start from the head or tail of the list, if an element is found, the location of the elements is in the location of the elements: Void Add (int index, object element): Add element Element Boolean Addall on the specified location Index (int index , Collection C): Add all elements of the collection C to the specified location index object get (int index): Returns the element INDEXOF (Object O) in the specified location in the list: Returns the position of the first element O, otherwise returns - 1 INT LastIndexof (Object O): Returns the position of the last element O, otherwise returns -1 Object Remove (int index): Delete Element Object Set on the specified location: Replace Location with Element ELEMENT INDEX The elements on, and returning the old element (2) The List interface is not only used in the entire list, but also handles the collection of subsets: listiterator listiterator (): Returns a list iterator to access the elements in the list Listiterator ListIterator (INDEX): Returns a list iterator to start accessing the element list sublist (int fromindex, int toindex) from the specified location index: Returns from the specified location fromNDEX (included) to toindex (not included) The list view of each element has an impact on the sub-list (such as add (), remove () and set () calls) have an effect on the underlying List. "2.1.Listiterator interface Listiterator interface inherits the Iterator interface to support the addition or change the underlying collection The elements in the middle 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 length N, having n 1 effective index value: (1) Void Add (Object O): Add object o to the front Void Set (Object O): Object O): Replace NEXT or Previous method Access the previous element. If the list structure is modified last time, ILLEGALSTATEEXCEPTION will throw an unlegation. (2) Boolean Hasprevious (): During the judge, if there is an element to access object previous (): Return to the previous object int nextIndex (): Returns the index of the elements of the elements returned next time, INT PreviousIndex (): Returns the index of the elements returned next time, "Under normal circumstances, no listiterator changes the direction of the collection element - forward or back. Although it can be implemented, prepVious () immediately calls Next (), Returning is the same element. Put the order of call next () and previous (), the same thing. "" We also need to explain the add () operation again. Add an element to cause new elements to be immediately Add to the front of the implicit cursor.
Therefore, the addition of the element to call previous () will return new elements, and NEXT () does not work, returns the next element before adding operation. "2.2.AbstractList, Abstract class has two abstract list implementation classes: AbstractList and AbstractSequentialList. Like the AbstractSet class, they override the equals () and havehcode () methods to ensure that two equal collection returns the same hash code If the two lists are equal and the same elements are the same as the order, the two lists are equal. The HashCode () here is specified in the List interface definition, but implemented here. In addition to equals () and havehcode (), AbstractList And AbstractSequentialList achieves part of the rest of the List method. Because data random access and order access is performed separately, making the creation of specific lists easier. The way you need to define depends on the behavior you want to support. You will never have to Featible is the implementation of the Iterator method. 2. The LinkedList class and the ArrayList class have two conventional List implementations in the Collection Framework: ArrayList and LinkedList. Which of the two LIST implementations 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, ArrayList provides an optional collection. But if you want to add and remove elements from the middle position of the list, as long as the order Access list elements, then LinkedList is better. "ArrayList and LinkedList implement the Cloneable interface, all provide two constructor, one-free, one accepts another collection" 2.3.1. LinkedList class LinkedList class Add some Handling the method of both end elements of the list. (1) Void AddFirst (Object O): Add object o to the list of the list of the list VOID ADDLAST (Object O): Add object o to the end of the list (2) Object getFirst (): return The element Object getlast (): Returns the element ending Elements (3) Object Removefirst (): Delete and return the element Object Removelast (): Delete and return the element ending Elements (4) LinkedList (): Build a Empty link list L INKEDLIST (Collection C): Build a list of links and add all elements of a collection C to use these new methods, you can easily treat LinkedList as a stack, queue, or other-oriented data structure. "2.3.2. ArrayList class ArrayList class encapsulates a dynamically redistributed object [] array. Each ArrayList object has a Capacity. This Capacity represents the capacity of the array of elements in the list. When the element is added to arraylist, its Capacity is automatically added in a constant time. In a program that adds a large number of elements to an ArrayList object, you can use the EnSureCapacity method to add Capacity. This can reduce the number of redistributions. (1) Void EnSureCapacity (int minCapacity): Capacity of ArrayList object Add MINCAPACITY (2) Void Trimtosize (): Soligible ArrayList object capacity is a list current size. Programs 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 set of repetitions, each particular SET implementation of the equivalent of the Equals () method of the added object 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 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 The positive value has twenty-four classes in Java 2 SDK version 1.4 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, that is okay. But if they are not equal, you should modify the comparison method, let the comparison methods and equals () effect. "Comparator Comparator (): Return to the elements to sort the elements The comparator, if the element is compared to the CompareTo () method of the Comparable interface, returns NULL (2) Object first (): Returns the first (minimum) element (3) Object last (): return The last (highest) element (4) SortedSet Subset (Object Fromelement): Return from FromenElement (included) to TOELEMENT Elements (Subsets) (5) sortedset headset (Object TOELEMENT): Return to a view of the SortedSet, which is less than TOEEEEMENT (Object Fromelement): Returns a view of the sortedset, each element is greater than or equal to FromenElement 3.4. AbstractStSet Abstract class AbstractSet class The equals () and havehCode () methods of the Object class are covered 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.com, (): Returns the Hash code of the object. The same object must return the same hash code 3.5. Hashset class, and Treeset class "Collection Frame" 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 (3) Hashset (int initialcapacity) : Build a empty helpless set (4) Hashset (int initialcapacity, float loadfactor) with a specific capacity: Build a holiday set with specific capacity and loading factors. LoadFactor is a number of 0.5.2 between 0.5.2. Treeset class (1) Treeset (): 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 "Comparer comparator without 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 (SortedSet S): Build a tree set, add all elements in an ordered set S, and use the same comparison as an ordered set S Sort by 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 set (2) LinkedHashSet: Build a link-type hash set and add all elements (3) LinkedHashSet (int initialcapacity): Build A empty chain terminal has a specific capacity (4) LinkedHashSet (Int Initialcapacity, Float LoadFactor): Build an empty chain terminal with specific capacity and load factor. LoadFactor is a number of 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. The 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 Action: Object Put (Object Key, Object Value): Place a keyword associated with each other with a value into 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. If the keyword does not exist, return NULL Object Remove: Remove the Mapp Putall (Map T) related to Key from the image: Add all elements from the specific image from the image: Give the image void clear (): Remove all mapping from the image and the value can be null. However, you cannot add Map to itself as a key or value. "(2) Query: Object Get (Object Key : Get the value associated with the keyword key, return to the object related to the keyword key, return Null Boolean ContainSkey (Object Key) if it is not found in the image, returns a keyword key in the image: KEY Boolean ContainSValue: The value of whether the image is present in the image (): Returns the number of maps in the current image Boolean ISempty (): Deconed whether there is any mapping in the image (3) view operation: Processing the image Middle key / value To group set keyset (): Return to all keywords in the image "Because the collection of key keys must be unique, you can use Set Support. You can also remove elements from the view, and the keywords are related to it The value will be 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 values in the map is not unique, you can support it with Collection. You can also The elements are removed in the view, while the values and its keyword will be deleted from the source image, but you can't add any elements. "Set entryset (): Returns the view set of map.Entry objects, namely the keywords in the image / Value "Because the mapping is unique, you can use set support. You can also remove the elements from the view, while these elements will be deleted from the source image, but you can't add any elements." 4.1. Map.entry interface MAP The 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 keyword (2) Object getValue (): Return to the entries (3) Object setValue (Object value): change the value in the related image to Value and return to the old value 4.2 The SortedMap Interface "Collection Frame" provides a special MAP interface: sortedMap, which is used to hold the orderly order of the key. 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 Then, the original key is replaced by the new value. If the two elements are equal, that is ok. But if not, you should modify the comparison method, make the comparison method and equals () effect. " 1) Comparator Comparator (): Returns the comparator used when you sort the keyword, return null (2) object firstKey () if the keyword is used to sort the keyword, return NULL (2) Object firstKey (): return to the first (Lowest) keyword (3) Object LastKey (): Return to the last (highest) keyword in the image (4) SortedMap Submap (Object fromkey, Object Tokey): Return from fromKey to ToKey (excluding) SortedMap view (5) sortedmap headmap (Object tokey): Returns a view of SortedMap, and the key of each element is smaller than tokey (6) sorted Tailmap (Object fromkey): Return to a view of SortedMap, The key of each element is greater than or equal to fromkey 4.3. AbstractMap abstract class and other abstract set implementations, 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" offer 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 In order to optimize the use of HashMap space, you can tune the initial capacity and load factor. (1) HashMap (): Build an empty hash image (2) HashMap (Map M): Build a hash image and add all mappings of the image M (3) Hashmap (int initialcapacity): Build a specific capacity Empty Hash Image (4) Hashmap (Int InitialCapacity, Float LoadFactor): Build an empty hash image with a specific capacity and load factor 4.4.2. TreeMap class TreeMap does not tune the option, because the tree is always equilibrium status.
(1) TreeMap (): Build an empty image tree (2) TreeMap (Map M): Build an image tree and add all elements (3) TreeMap in the image m: Build an image tree and use The specific comparator is sorted (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. 5. LINKEDHASHMAP class LinkedHashMap extension HashMap In the insert order, the keyword / value is added to the link hash image. 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 specific Empty Link Hash Image (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 factor, and access order. "If you set AccessOrder to True, the link hash image will use access order instead of iteration of each image. Each image is used. Each time you call GET or When the PUT method, the relevant mapping is deleted from its current location, and then placed at the end of the link image list (only the location in the list of linked images will be affected, the hash table is not affected. ha Xi Table Mapping always stays in the hash of the hash code corresponding to the keyword). "" This feature is useful for implementing the principle of "deleting the least recently used" in cache. For example, you can hope Often access maps are saved in memory and read objects that do not access often from the database. When you find a map in the table, and the mapping in the table has been very full, you can make iteration Enter the table, delete the beginning of the beginning of the beginning. These are the most recent mappings. "(6) Protected Boolean RemoveEldestentry (map.entry Eldest): If you want to delete the oldest map, override This method is 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 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.