------Collection of Java

Source: Internet
Author: User
Tags collator comparable set set

Collection


first, the concept of a collectionwritten Explanation: A collection is a simple object that contains more than one object, and the contained object is called an element. A collection can contain any number of objects, the quantity can vary, and there is no limit to the type of the object, which means that all objects in the collection can be of the same type or different. Set: Unlimited number, type unlimited; arrays: fixed length, single type.
Personal Understanding: A collection is an extension of an array, where the collection can hold a variety of data types and objects, while the collection can be freely expanded, that is, free to add elements, and arrays cannot, which is far more powerful than arrays. You can also use a collection in mathematics to understand the collection, and the elements in the collection cannot be duplicated.
II. data storage structure Classificationarrays are stored sequentially, and collections are stored in a richer and more powerful way: (1) sequential storage (2) chained storage (3) tree storage (4) hash store hash (5) map map Store
three, set frame

The six collections in "implementation" in the figure are used more, and the "Historical Collection class" is now less used.
1. Features of each interface in the set frame 1) Collection InterfaceThe collection interface is a set of objects that allow duplicates
The collection interface is used to represent any object or group of elements. This interface is used when you want to handle a set of elements in the usual way possible.
It also uses the iterator interface, the iterator iterator, to enumerate the elements in the collection. It's a good idea to do ACM, which is simple to understand: put all the elements in the collection in an iterator (a close-up container), and then iterate through all of the content implementation classes: HashSet, ArrayList, Linkedlis:
Package cn.hncu.collection;  Import java.util.ArrayList;  Import java.util.Collection;  Import Java.util.HashSet;    Import Java.util.Iterator; public class Collectiondemo {public static void main (string[] args) {collection<object> col=new Ar          Raylist<object> ();          Use ArrayList () here to add the order of what sequence then he stores is what order//Collection col=new HashSet ();          If you use HashSet () to do this, the storage method is based on its hash value, the position is indeterminate,//But the overall sort is: the numbers are sorted in order of size, and the strings are sorted by character encoding;          Col.add (1);          Col.add (2);          Col.add (6);          Col.add ("Jack");                    Col.add ("Tom"); ※ Note that if the implementation class is hashset, then the stored location of the element being added is determined by the hashcode value of each element//At this time, when the Perosn class does not overwrite hashcode, the position of the person object is indeterminate,          So its hashcode is the memory address of the object. In conclusion, if you want to determine the position of the object, you need to overwrite the hashcode ()//If the element is a class object, then its hash value is the return value of the Hashcode () method,//So if you write the Hashcode () method returns the same value, it is considered          is the same element, Col.add (New person ("John", 21)); Col.add (New person ("Jane", 19));  Delete//Col.remove (2);                    Col.add ("AA");                    Change 1//Col.remove (1); Col.add (1);          Change 2//This kind of modification, if the use of hashset words, regardless of how the change will be sorted by the hashcode value of the storage,//And if the use of ArrayList, the elements that need to be modified where the original changes will be where;          For the above modification 1 the same applies to the secondary principle Object objs[]=col.toarray ();          Col.clear ();              for (int i=0;i<objs.length;i++) {if (Objs[i].equals (1)) {objs[i]= "100";          } col.add (Objs[i]);          } iterator<object> It=col.iterator ();              while (It.hasnext ()) {Object obj=it.next ();          System.out.println (obj);   }      }  }
2) Set interfaceby definition, the set interface inherits the collection interface, and it does not allow duplicates to exist in the collection. All the original methods are readily available in collection and no new methods are introduced. The specific set implementation class relies on the Equals () method of the added object to check for equivalence. When set adds an element, it is bound to execute the hashcode () method of the element being added, sorted by this.
Implementation classes: HashSet, TreeSet
3) List interfaceThe list interface inherits the collection interface to define an ordered set of allowed duplicates. This interface is not only able to process a part of the list, but also adds a location-oriented operation. Location-oriented operations include the ability to insert an element or collection, and also to get, drop, or change the functionality of an element. Searching for elements in the list can start with the head or tail of the listing, and if the element is found, it will also report where the element is located (this is a powerful, position-capable operation).
when the list and its implementation class objects are added and censored, the location operation can be specified to operate the specific location. such as E.add (1,800); To insert an integer 800 in a 1 position, the original 1 position and the following elements will all move backward one position, as well as E.removefirst (), and E.removelast (); To remove an element from the front and back (where remove is a return value, you need to define a variable to be received), and then you have to reorder it after adding or removing changes. A) The Hashcode () method is not called automatically when A list (such as ArrayList) is used. Because in the list, repeating is repeated, do not need to judge.
B) The list has added the function of subscript index, so that the modification of the list can use the Set method to replace the elements of the specified position directly, do not need to be as complex as set (to convert the array to modify, and then to convert back).
C) collection with a iterator iterator, and list can be used with a listiterator listing iterator. The former can only be next (), which contains not only the next () method, but also the previous () method. Therefore, if you want to use the list to do similar to the book page, you can not only flip backwards, but also forward.
Implementation classes: ArrayList, LinkedList 4) Map Interfacethe map interface is not an inheritance of the collection interface. Instead, start with your own interface hierarchy for maintaining key-value associations. By definition, this interface describes a key-to-value mapping that is never duplicated.
This interface method can be divided into three sets of operations: changing, querying, and providing an optional view.
The change operation allows you to add and remove key-value pairs from the map. Both the key and the value can be null. However, you cannot add a map as a key or value to itself.
The Map.entry interface (entry is the inner class in the map interface): The map's EntrySet () method returns an object set set that implements the Map.entry interface, where each object is a specific key-value pair in the underlying map.
Implementation classes: HashMap, TreeMap
2. Realization class 1) ArrayList, LinkedListwhich of the two lists is implemented depends on the specific need: if you want to support random access without inserting or removing elements at any point except the trailer, ArrayList provides an optional collection.
However, if you want to add and remove elements frequently from the middle of the list, and as long as the sequential access list element, then the LinkedList implementation is better.
Boolean add(E e)
Adds the specified element to the tail of this list.
void add(int index,E element)
Inserts the specified element into the specified position in this list.
 E get(int index)
Returns the element at the specified position in this list.
Boolean isEmpty()
If there are no elements in this list, the return true
 E remove(int index)
Removes the element at the specified position in this list.
 E set(int index,E element)
Replaces the element at the specified position in this list with the specified element.
Int size()
Returns the number of elements in this list.

Note: In addition, LinkedList adds some methods for working with the elements on both sides of the list, which make it easy to use LinkedList as a stack, queue, or other endpoint-oriented data structure.

void addFirst(E e)
Inserts the specified element at the beginning of this list.
void addLast(E e)
Adds the specified element to the end of this list.
 E getFirst()
Returns the first element of this list.
 E getLast()
Returns the last element of this list.
 E removeFirst()
Removes and returns the first element of this list.
 E removeLast()
Removes and returns the last element of this list.

2) HashMap, TreeMapwhich implementation is used depends on the specific needs:HashMap is the best choice for inserting, deleting, and locating elements in a map. But if you want to traverse the keys sequentially, then TreeMap is better. The key class that is added with HashMap requires a clear definition of the hashcode () implementation (understanding: Map.keyset Returns the set set of keys, and the set set has a limit on the hashcode implementation, so the class that is the key is also subject to that restriction). With the TreeMap implementation, the elements added to the map must be sortable.
Note: Both HashMap and TreeMap implement the Cloneable interface. when you need to traverse the elements, the key view and the EntrySet view before traversing will need to get map map to put into the collection and then use the iterator to traverse, the following keyset view as an example to paste the small block code (EntrySet view is similar):set<object> Entries=map.entryset ();
Iterator<object> It2=entries.iterator ();
while (It2.hasnext ()) {
Entry<object, object> entry= (Entry) it2.next ();
System.out.println ("key=" +entry.getkey () + ", value=" +entry.getvalue ());
}
The value view is different, it uses the collection interface, and the following is also a small block code:Collection<object> value=map.values ();
Iterator<object> It3=value.iterator ();
while (It3.hasnext ()) {
Object Obj=it3.next ();
String str=obj.tostring ();
System.out.println (str);
}
3) HashSet class and TreeSet classthe "set framework" supports two common implementations of the set interface: HashSet and TreeSet. In more cases, HashSet stores the collection of repeated liberties. With efficiency in mind, objects added to the hashset need to implement the Hashcode () method in a way that distributes the hash code appropriately. The TreeSet implementation is useful when you need to extract elements in an orderly manner from the collection. To be able to proceed smoothly, the elements added to the TreeSet must be sortable.
because TreeSet is ordered, sorting uses the sort method of the sorted element (COMPARETO)----The abstract method in the comparable interface, so using TreeSet, The object element that is added to it must implement the interface (not the element of the object hashcode the element itself), and the element that joins the collection does not implement the comparable interface because HashSet is not ordered.
Add (Note): When TreeSet calls the Add () method, it causes the newly added element to call the CompareTo (obj) method, which in turn passes the existing element as a parameter, making the decision size, from the previous sentence, Decide which elements to put in the Treexxx collection to implement the comparable interface. However, when the added element is inconsistent with an existing element type, the CompareTo (obj) method of the newly added element will force the comparison of the existing element into its type, and the classcastexception exception will occur. such as (employee is the class that has been written):Set.add (111);
Set.add ("AAA");
Set.add ("BBB");
Set.add (New Employee ("Zhang San", 22));
Set.add (New Employee ("John Doe", 25));
Set.add (New Employee ("Jack", 23));

Iv. sorting of sets Method 1:the Java.lang.Comparable interface works when a class has a natural order. The object collection is assumed to be of the same type, which allows the collection to be sorted into natural order.
The int compareTo (T obj) method in this interface compares the current instance object with Object obj, returns a negative value if it precedes the object obj, returns 0 if the two objects are in the same position in the sort, or returns a positive value if it is behind the object obj.
The implementation point of this sort method is to let the object class that is placed into the container implement the comparable interface. The method that is implemented by CompareTo () determines the order in which objects are arranged.

Method 2:the Java.util.Comparator interface works when a class has a natural order. The object collection is assumed to be of the same type, which allows the collection to be sorted into natural order.
The compare (T O1, To2) method in this interface: compares the two parameters used to sort. Returns a negative, 0, or positive integer based on the first parameter less than, equal to, or greater than the second parameter
the implementation point of this sort method is to have the container join the Comparer object at construction time.
Chinese sorting problem:
Comparison functions are not problematic for sorting characters in ASCII codes such as letters and numbers, but the Chinese sort is obviously incorrect. This is mainly in Java in the use of Chinese encoding GB2312 or GBK, char type conversion to int type of process has a relatively large deviation. This deviation is caused by the Compare method, so we can implement the comparator interface ourselves. In addition, the internationalization problem can be solved by collator class.
The Java.text.Collator class, which provides classes and interfaces for handling text, dates, numbers, and messages in a way unrelated to natural language.
Here is an example of comparator:
Package cn.hncu.sort3;  Import Java.util.Comparator;  Import Java.util.Iterator;  Import Java.util.Map;  Import Java.util.Set;  Import Java.util.TreeMap;  Import Java.util.Map.Entry;  Import Java.text.CollationKey;  Import Java.text.Collator;    Import Java.util.Comparator;  public class Sort3demo {public static void main (string[] args) {comparator<object> comparator2=new          MYCMP2 ();          Treemap<object, object> map=new treemap<object, object> (COMPARATOR2);          Map.put ("Zhou June", "1001");          Map.put ("Zhang June", "1002");          Map.put ("Li FG Army", "1003434");                    Map.put ("Liu Yijun", "1004555");          Set Entries=map.entryset ();          Iterator<object> It=entries.iterator ();              while (It.hasnext ()) {map.entry entry= (Entry) it.next ();          System.out.println ("key=" +entry.getkey () + ", value=" +entry.getvalue ()); }}} class MYCMP2 implements comparator{@Override public int CoMpare (Object O1, Object O2) {Collator collator=collator.getinstance ();          Collationkey Key1=collator.getcollationkey (o1.tostring ());          Collationkey Key2=collator.getcollationkey (o2.tostring ());  Return Key1.compareto (Key2);   Return Key2.compareto (Key1);//Reverse}}
Application for collection sorting:in JDK1.2, there are 14 classes that implement the comparable interface, and the natural sort specified in these classes is as follows:
1, bigdecimal,biginteger,byte,double,float,integer,long,short by number size
2. Character by the numeric size of the Unicode values
3, Collationkey by locale-sensitive string sorting
4. Date chronological order
5. File sorted by Unicode value of the fully qualified character of the system-specific path name
6. Objectstreamfield Sort by the Unicode value of the characters in the name
7. String sorted by character Unicode value in string
if a class cannot or does not facilitate the implementation of the Java.lang.Comparable interface, it can provide its own sorting behavior using the method that implements the comparer comparator interface. Similarly, if the default comparable behavior does not meet the engineering needs, you can also provide your own comparator.


------Collection of Java

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.