Java Collection Framework

Source: Internet
Author: User
Tags comparable set set sorts

Java Collections Overview

On the one hand, object-oriented language is the embodiment of things in the form of objects, in order to facilitate the operation of multiple objects, it is necessary to store objects. On the other hand, there are drawbacks to using an array to store objects, and Java collections are like containers that dynamically place references to multiple objects into a container.

· The Java Collection class can be used to store multiple objects of varying amounts, and it can be used to hold associative arrays that have a mapping relationship.

· Java collections can be divided into collection and map two systems

Collection interface:

Set: An unordered, non-repeatable collection of elements---similar to a high school collection

List: Elements ordered, repeatable sets---dynamic arrays

Map interface: A collection of "key-value pairs" with a mapping relationship---"functions" similar to high school

Collection interface

· The collection interface is the parent interface of the list, set, and queue interfaces, and the methods defined in the interface can be used to manipulate both the set set and the list and queue collections.

· The JDK does not provide any direct implementation of this interface, but rather provides a more specific implementation of the sub-interfaces (such as: Set and list).

• Before Java5, the Java collection loses the data type of the objects in the container

Collection Interface method

Traversing a collection element using the iterator interface

· The iterator object is called an iterator (one of the design patterns) and is used primarily to traverse the elements in the collection collection.

• All collection classes that implement the collection interface have a iterator () method that returns an object that implements the iterator interface.

· Iterator is used only to iterate through the collection, and iterator itself does not provide the ability to load objects. If you need to create a iterator object, you must have a collection that is iterated.

Method of Iterator interface

You must call It.hasnext () for detection before calling the It.next () method. If not called and the next record is invalid, calling It.next () directly throws a Nosuchelementexception exception.

· Java 5 provides an iterative access to the Foreach Loop collection

for (type) p (traversed element name):p Ersons (the collection name to traverse)) {

P.getname ();

}

List interface

Limitations of arrays used to store data in Java

· The elements in the list collection class are ordered and repeatable, and each element in the collection has its corresponding sequential index.

· The elements in the list container correspond to an integer-type ordinal access element in the container.

· The implementation classes for the list interface in the JDK API are commonly used: ArrayList, LinkedList, and vectors.

· The list collection adds some methods to manipulate the collection elements according to the index.

void Add (int index, Object ele) boolean addall (int index, Collection eles) object get (int index) int indexOf (Object obj ) int LastIndexOf (object obj) object Remove (int index) object Set (int index, object ele) List sublist (int fromIndex, I NT Toindex) One of the list implementation classes: ArrayList ArrayList is a typical implementation class of the list interface • Essentially, ArrayList is a variable-length array of object references
· ArrayList is thread insecure, and vector is thread safe, even if the Vectorlist implementation class is not recommended to ensure the list collection thread safety: LinkedList for frequent insertions or deletions of elements, it is recommended to use the LinkedList class , high Efficiency • New method: void AddFirst (Object obj) void AddLast (Object obj) object GetFirst () object GetLast () object Removefirst () Object removelast () set interface • The set interface is a sub-interface of the collection, and the set interface does not provide additional methods · The set collection does not allow the same elements to be included, and if you try to add two identical elements to the same set set, the addition operation fails. Set determines whether two objects are the same, not using the = = operator, but by the Equals method. one of the set implementation classes: HashSet· HashSet is a typical implementation of the set interface, which is used most of the time when the set collection is used. HashSet stores the elements in the collection by a hash algorithm, so it has good access and lookup performance. HashSet has the following characteristics: The ordering of elements cannot be guaranteed HashSet the collection element that is not thread safe can be null when an element is saved to the HashSet collection, HashSet calls the Hashcode () method of the object to get the Hashco of the object De value, and then determines where in HashSet the object is stored, based on the hashcode value. The HashSet collection determines the criteria for equality of two elements: two objects are compared by the hashcode () method, and the Equals () method return values for two objects are also equal. Hashcode () method • If the Equals () method of two elements returns true, but their hashcode () return values are not equal, HashSet will store them in a different location, but they can still be added successfully. • For objects stored in the set container,  The corresponding class must override the Equals () and Hashcode (Object obj) methods to implement the object equality rule. • Overriding the basic principles of the Hashcode () method when the program runs, multiple calls to the Hashcode () method on the same object should return the same value When the Equals () method of two objects returns True, the return value of the Hashcode () method of both objects should also be used as the Equals () method in the object's comparison field, should be used to calculate the Hashcode value set implementation class two: Linkedhsahset Linkedhashset is a subclass of HashSet · Linkedhashset determines where an element is stored based on the hashcode value of the element, but it maintains the order of the elements using the linked list, which makes the elements appear to be saved in the order in which they were inserted. Linkedhashset Insert performance is slightly lower than hashset, but it performs well when iterating through all the elements of the set. Linkedhashset does not allow collection elements to be duplicated. The third of the Set implementation class: TreeSet TreeSet is an implementation class for the SortedSet interface, TreeSet can ensure that the collection element is in sort state   Comparator Comparator () object first () object last () object low ER (object E) object higher (object e)   SortedSet subset (fromelement, toelement) SortedSet HeadSet (toelement) SortedSet tailset (fromelement) · TreeSet two ways to sort: natural sorting and custom sorting. By default, TreeSet uses natural sorting. Sort-natural Sort • Natural sort: TreeSet invokes the CompareTo (Object obj) method of the collection element to compare the size relationship between elements, and then arranges the collection elements in ascending order • If you attempt to add an object to TreeSet, the object's class must implement  Comparable interface. A class that implements comparable must implement the CompareTo (object obj) method, and two objects compare the size by the return value of the CompareTo (object obj) method. Typical implementations of the comparable: BigDecimal, BigInteger, and all of the numerical types corresponding to the wrapper classes: compare them by their corresponding numerical sizes Character: Compare by the Unicode values of the characters boolean:true The corresponding wrapper class instance is greater than false for the wrapper class instance string: Compares the Unicode value of a character in a string by the date, time: The moment after, the date is greater than the previous time, and the date is larger • When adding elements to TreeSet Only the first element does not have to compare the CompareTo () method, and all the elements that are added later call the CompareTo () method for comparison. • Because only two instances of the same class compare size, add objects to the same class to the TreeSet • for TreeSet Collection, it is the only criterion that determines whether two objects are equal: Two objects compare the return value with the CompareTo (object obj) method • When you need to put an object into TreeSet, overriding the Equals () method for that object, you should ensure that the method The CompareTo (Object obj) method has a consistent result: If two objects return true through the Equals () method, the comparison by the CompareTo (object obj) method should return 0 · The natural ordering of TreeSet is the ascending order of elements according to the size of the collection elements. If you need custom sorting, such as descending order, you can use the help of the comparator interface. Need to rewrite compare (T o1,t O2) method. • Use the int compare (T o1,t O2) method to compare the size of O1 and O2: If the method returns a positive integer, the O1 is greater than O2, if 0 is returned, it is equal, and a negative integer is returned, indicating that the O1 is less than O2. • To achieve custom sorting, You need to pass an instance of the implementation comparator interface as a parameter to the TreeSet constructor. • At this point, you can still add only objects of the same type to TreeSet. Otherwise, a classcastexception exception occurs. • Use custom sorting to determine the criteria for two elements being equal: Two elements are returned 0 by comparator comparison.  map Interface · Map and collection exist in parallel. Data to be used to save A; Map relationship: Key-value Both key and value in the map can be data of any reference type · The key in the map is stored with set, which is not allowed to be duplicated, that is, the class corresponding to the same map object, the Hashcode () and the Equals () method must be overridden. • A one-way relationship exists between the commonly used string class as the "key" key and value of the map That is, the key can always find a unique, definite value. Map Common methods • Add and delete operations: Object put (object Key,object value) object Remove (object key) void Putall (Map t) void Clear () Meta View Operation method: Set KeySet () Collection values () set EntrySet () • Element query operation: Object get (Object key) Boolean ContainsKey (Object key) Boolean Containsvalue (object value) int size () Boolean isEmpty () Boolean equals (Object obj) One of the map implementation classes: HashMap Common implementation classes for map interfaces: HashMap, TreeSet, and properties. HashMap is the most frequently used implementation class for the map interface. • Null keys and null values are allowed, as with hashset, the order of mappings is not guaranteed · HashMap the criterion for determining the equivalent of two keys is that two keys return the True,hashcode value by means of the Equals () method. • HashMap the criterion for determining the equality of two value is: Two value returns true through the Equals () method. Map Implementation Class II: LinkeDhashmap Linkedhashmap is a subclass of HashMap. • Similar to Linkedhashset Linkedhashmap can maintain the iteration order of the map: Iteration order: The sequence of iterations is consistent with the insertion order of Key-value pairs map implementation class Three: TreeMap TreeMap you store key-value pairs, you need to sort them according to Key-value. TreeMap can ensure that all key-value are in an orderly state. Sort of TreeMap key: Natural sort: TreeMap All keys must implement the comparable interface, and all keys should be objects of the same class, otherwise the classcastexception custom sort will be thrown: when creating TreeMap, Passes in a comparator object that is responsible for sorting all keys in the TreeMap. You do not need the key of map to implement comparable interface at this time · TreeMap Two keys equal to the standard: Two keys are returned 0. by the CompareTo () method or the Compare () method If you use a custom class as TreeMap key, the owning class needs to override the Equals () and Hashcode () methods, and Eqauls () returns True, the CompareTo () method should return 0. Map implementation Class Four: Hashtable Hashtable is an old map implementation class, thread safe. Unlike HashMap, Hashtable does not allow NULL as key and value as with HashMap, Hashtable does not guarantee key-value to the order Hashtable determine the two keys equal, Two value equal to the standard, with HashMap has been. Map implementation class Five: Properties The properties class is a subclass of Hashtable, which is used to process property files • Both the key and the value in properties are string types because the key and value in the property file are string types. • When accessing data, We recommend using the SetProperty (string key,string value) method and the GetProperty (string key) method    Example: Properties Pros = new properties (); Pros.load (New FileInputStream ("Jdbc.properties")); String user = Pros.getpropErty ("user"); System.out.println (user);  tool class for Operation Collection: Collections Tool class for manipulating arrays: arrays Collections is a tool class that operates collections of set, list, and map. Collection provides a series of static methods for sorting, querying, and modifying collection elements, and also provides methods for setting immutable set objects, synchronizing control of collection objects, and so on. • Sort operations: (both static methods) reverse (List) : Reverses the order of the elements in the list Shuffle (list): Randomly sorts the list collection elements sort (list): Sorts the specified list collection elements in ascending order based on the natural ordering of the elements sort (list, Comparator): Sorts the List collection elements according to the order of the specified Compareator (list,int,int): Swaps the I and J elements in the specified list collection · Object Max (Collection): Returns the largest element in the specified collection according to the natural order of the element · Object Max (Collection,comparator): Returns the largest element in a given set, based on the order specified by Comparator · Object min (Collection) · Object min (collection,comparator) int frequency (Collection,object): Returns the number of occurrences of the specified element in the specified collection void copy (List dest,list SRC): Copy content from src to dest boolean replaceall (list List,object oldval,object newval): Replaces all old values of the list object with the new value synchronization control · Multiple synchronizedxxx () methods are available in the collections class, which enables you to wrap a specified collection as a collection of thread synchronizations, which resolves thread-safety issues when multithreading concurrently accesses a collection

Java Collection Framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.