Dark Horse Programmer------Java Collection Framework Learning Summary

Source: Internet
Author: User
Tags comparable set set

Java training, Android training, iOS training,. NET training. Looking forward to your communication

First, the summary

All collection classes are located under the Java.util package. Only objects can be saved in the collection (a reference variable that holds the object). (Arrays can hold both basic types of data and objects).

The Java Collection class is primarily derived from two interfaces: Collection and map,collection and map are the root interfaces of the Java Collection framework, which in turn contains some interfaces or implementation classes.

Second, Collection Interface

Collction:

List : Orderly ( The order in which elements are stored in the collection is consistent with the order taken ) , the elements are indexed. Elements can be duplicated.  

Set: Unordered (the deposit and fetch order may be inconsistent), cannot store duplicate elements. Element uniqueness must be guaranteed.

1. Add:

Add (object): Adds an element AddAll (Collection): Adds all the elements in a collection.

2. Delete:  

Clear (): Removes all elements from the collection, emptying the collection. Remove (obj): Deletes the specified object from the collection. Note: The length of the collection will change if the deletion succeeds. RemoveAll (collection): deletes some elements. Some elements are consistent with incoming collection.

3. Judgment:

Boolean contains (obj): whether the specified element is contained in the collection. Boolean Containsall (Collection): Whether the collection contains the specified number of elements. Boolean isEmpty (): whether there are elements in the collection.

4. Get:

Boolean contains (obj): whether the specified element is contained in the collection. Boolean Containsall (Collection): Whether the collection contains the specified number of elements. Boolean isEmpty (): whether there are elements in the collection.

5. To take the intersection:

Boolean  Retainall (Collection): The same element in the current collection that is persisted and specified in the collection. Returns flase if the two collection elements are the same, or true if Retainall modifies the current collection.

6. gets all the elements in the collection:   

Iterator  

7. to turn a collection into an array:

Iterator  

List Interface:  

The list itself is a sub-interface of the collection interface and has all the collection methods.

Now learning the common method peculiar to list system, the method of lookup finds that the unique method of list has index, which is the most characteristic of this set.

List : Orderly ( The order in which elements are stored in the collection is consistent with the order taken ) , the elements are indexed. Elements can be duplicated.

ArrayList : the underlying data structure is an array , thread is out of sync, ArrayList replaced the Vector , the query element is very fast.  

LinkedList : the underlying data structure is linked list, the thread is not synchronized, the speed of adding or deleting elements is very fast.  

Vector : the underlying data structure is the array, the thread synchronizes, Vector regardless of query and additions and deletions are huge slow.

1. Add:

2. Delete:

3. Get:     

Object Get (Index): Gets the specified element by index.

int indexOf (obj): Gets the index bit of the first occurrence of the specified element, if the element does not exist return-1, and 1 to determine whether an element exists.

int lastIndexOf (Object o): Reverse index Specifies the position of the element.

List sublist (start,end): Gets the child list.  

4. Modify:    

5. get all elements:  

Listiterator Listiterator (): A list collection-specific iterator.

List The collection supports adding, deleting, changing, and checking elements.

List The collection is because the corner label has its own way of acquiring the element:

Traverse   

for (int x=0; x<list.size (); x + +) {

SOP ("Get:" +list.get (x));

}

When iterating through the list elements, if you want to manipulate elements during an iteration, such as satisfying a condition to add a new element. will occur . Concurrentmodificationexception Concurrency modification exceptions.  

the causes are:

A collection reference and an iterator reference operate an element at the same time, and after the collection is fetched to the corresponding iterator, the element that is referenced by the collection is added in the iteration, and the iterator does not know, so an exception occurs.

How to solve it?  

Now that you are working with elements in an iteration, it is most appropriate to find an iterator. But there are only hasnext,next,remove methods in iterator. By looking at its sub-interface, Listiterator, the list iterator interface has the added, deleted, modified, Check the action.

Listiterator is an iterator that is unique to the list collection.

Listiterator it = list.listiterator;//Replaces iterator it = list.iterator;  

code example:

Import java.util.*;/* Note: The parameter type of the 1,add method is object. To make it easy to receive any type of object. 2, the collection is stored in the object's reference (address) */classcollectiondemo{public static voidMain (string[] args) {method_get (); } public static voidMethod_get () {ArrayList Al = newArrayList ();        1, add the element.        Al.add ("Java01");//add (Object obj); Al.add ("Java02"); Al.add ("Java03"); Al.add ("Java04"); /* Iterator it = al.iterator ();//Gets the iterator that is used to remove the elements from the collection. while (It.hasnext ()) {SOP (It.next ());} */for (Iterator it =Al.iterator (); It.hasnext (); ) {SOP (It.next ());}} public static voidMethod_2 () {ArrayList al1 = newArrayList (); Al1.add ("Java01"); Al1.add ("Java02"); Al1.add ("Java03"); Al1.add ("Java04" ); ArrayList Al2 = new  ArrayList () al2.add ("java03" ); Al2.add ("Java04" ); Al2.add ("java05" ); Al2.add ("java06" );//al1.retainall (AL2);//go to intersection, AL1 will only retain the same elements in Al2.  Al1.removeall (AL2); SOP ("Al1:" +  al1); SOP ("Al2:" +  Al2);} public static void  Base_method () {//Creates a collection container. Subclasses that use the collection interface. ArrayList ArrayList al = new  ArrayList ();//1, add element. Al.add ("Java01");//add (Object obj); Al.add ("JAVA02" ); Al.add ("java03" ); Al.add ("Java04" );//Print the original collection. SOP ("Original set:" +  AL); 3. Delete the element. Al.remove ("Java02"); Al.clear ();//emptying the collection. 4, judging elements. SOP ("JAVA03 is present:" +al.contains ("Java03" )); SOP ("Is the collection empty? "+  Al.isempty ()); 2, get the number. The collection length. SOP ("Size:" +  al.size ()); Prints the changed collection.  SOP (AL);} public static void  sop (Object obj) {System.out.println (obj);}        

Set Interface:  

The methods in the set interface are consistent with the methods in the collection. The set interface is removed in only one way, an iterator.

HashSet : The underlying data structure is a hash table, and threads are not synchronized. disorderly, efficient;

HashSet The Collection guarantees element uniqueness: It is done through the Hashcode method of the element and the Equals method. When the hashcode value of the element is the same, it continues to determine whether the equals of the element is true. If true, then the same element is considered not saved. If False, then store. If the hashcode value is different, then equals is not judged, thus increasing the speed of object comparisons.

Linkedhashset : Orderly, HashSet sub-class .

TreeSet : Sorts the specified order of the elements in the set collection. Different steps. TreeSet the underlying data structure is a binary tree.

the principle of a hash table:  

1. For the key words in the object element (unique data in the object), the hash algorithm is computed and a specific algorithm value is obtained, which is called the hash value.

2. The hash value is the position of this element.

3. If there is a conflict in the hash value, re-determine whether the same object is the same for this keyword. If the objects are the same, they are not stored because the elements are duplicated. If the object is different, it is stored and deferred on the original object's hash value base +1.

4. The structure that stores the hash value, which we call a hash table.

5. Since the hash table is stored on a hash value, it is best to ensure that the object's keywords are unique for efficiency. This can be as few as possible to determine whether the corresponding object of the same keyword, improve the operation efficiency of the hash table.

For ArrayList sets, it is the Equals method to determine whether an element exists or to delete an element's underlying basis.

For HashSet collections, determine whether an element exists, or delete an element, based on the Hashcode method and the Equals method.

TreeSet:

Used to sort the specified order of elements in the set collection, and the ordering needs to be based on the comparison of the elements themselves.

if the element is not comparable, it will occur at run time classcastexception exception.

So we need elements to implement comparable interface, forcing elements to have a comparative, CompareTo method of replication. Determines the position of the element in the TreeSet data structure, based on the return value of the CompareTo method.

The TreeSet method guarantees the uniqueness of the element by means of a reference to whether the result of the comparison method is 0, and if return 0 is treated as a two object repetition, does not exist.

Note: when comparing, if the judgment element is not unique, for example, the same name, the same age, only as the same person. in the judgement, the main conditions and secondary conditions need to be divided, when the main conditions are the same, then judge the secondary conditions, sorted by the secondary conditions.

TreeSet There are two ways to sort a collection, comparable and the Comparator difference:

1: Let the element itself have the comparison, need element object implements comparable interface, overwrite CompareTo method.

2: To make the collection itself comparable, you need to define a comparer that implements the comparator interface, override the Compare method, and pass the class object as the actual argument to the TreeSet collection's constructor.

The second approach is more flexible.

Map Collection:

    Hashtable: The underlying is a hash table data structure that is thread-synchronized. You cannot store null keys, null values.

    HashMap: The underlying is a hash table data structure that is not synchronized by threads. You can store null keys, null values. Replaced the Hashtable.

    TreeMap: The bottom layer is a two-fork tree structure that allows you to sort the keys in the map collection in a specified order.

Map Collection Storage and Collection There are a lot of differences:  

Collection one element at a time; map saves a pair of elements at a time. Collection is a single-column collection;

A pair of elements stored in a map: A key, a value, and a corresponding (mapping) relationship between the key and the value.

Features: To ensure the uniqueness of the keys in the map set.

1. added.

Put (Key,value): When the stored key is the same, the new value replaces the old value and returns the old value. Returns NULL if the key is not duplicated. void Putall (MAP);

2. deleted.

3. judgment.

4. removed.

code example:

/*Map Collection: The collection stores key-value pairs. A pair of pairs went into the deposit. and to guarantee the uniqueness of the key. Map | HashMap: The underlying is a hash table data structure that allows NULL values and NULL keys, which are not synchronized. Replace Hashtable, jdk1.2. High efficiency. |--treemap: The bottom layer is a two-fork tree data structure. Thread is out of sync. Can be used to sort the keys in the map collection. */ImportJava.util.*;classmapdemo{ Public Static voidMain (string[] args) {Map<String,String> map =NewHashmap<string,string>(); //Adds an element, adding an element if the same key appears when added. Then the added value overrides the original key corresponding value. //The Put method returns the overridden value. System.out.println ("Put:" +map.put ("the", "Zhangsan1")); System.out.println (Put: "+map.put", "Wnagwu")); Map.put ("Zhangsan2", "the"); Map.put ("Zhangsan3", "the"); System.out.println ("ContainsKey:" +map.containskey ("022")); //System.out.println ("Remove:" +map.remove ("the");System.out.println ("Get:" +map.get ("023")); Map.put ("04",NULL); System.out.println ("Get:" +map.get ("04"));//The return value of the Get method can be used to determine whether a key exists.              Judged by returning null. //gets all the values in the Map collection. collection<string> coll =map.values ();        System.out.println (coll);    SYSTEM.OUT.PRINTLN (map); }}

5. want to get Map all of the elements in:

The extraction principle of the Map collection: The Map collection is turned into a set set. is removed by an iterator.

1. set<k> KeySet: Deposit all the keys in the map into the set set. Because set has iterators. All the keys that can be iterated out are taken in accordance with the Get method. Gets the value corresponding to each key.

2. Set<map.entry<k,v>> EntrySet: The mapping relationship in the map collection is stored in the set set, and the data type of the relationship is: map.entry

Sample fetch method code for map collection:

/*each student has a corresponding place of attribution. Student student, address string. Student attributes: Name, age. Note: The same name and age are regarded as the same student. Ensure the uniqueness of students. */ImportJava.util.*;classStudentImplementsComparable<student>{    PrivateString name; Private intAge ; Student (String name,intAge ) {         This. Name =name;  This. Age =Age ; }    //the method of carbon comparable     Public intCompareTo (Student s) {intnum =NewInteger ( This. Age). CompareTo (NewInteger (s.age)); if(num==0)            return  This. Name.compareto (S.name); returnnum; }     Public inthashcode () {returnName.hashcode () +age*34; }     Public Booleanequals (Object obj) {if(! (objinstanceofStudent)) Throw NewClassCastException ("Type Mismatch"); Student s=(Student) obj; return  This. Name.equals (S.name) && This. age==S.age; }     PublicString GetName () {returnname; }     Public intGetage () {returnAge ; }     PublicString toString () {returnName+ ":" +Age ; }}classmaptest{ Public Static voidMain (string[] args) {HashMap<Student,String> HM =NewHashmap<student,string>(); Hm.put (NewStudent ("Lisi1", +), "Beijing"); Hm.put (NewStudent ("Lisi1", +), "Tianjin"); Hm.put (NewStudent ("Lisi2", "Shanghai"),); Hm.put (NewStudent ("Lisi3"), "Nanjing"); Hm.put (NewStudent ("Lisi4", "Wuhan")); //The first method of removal KeySetSet<Student> KeySet =Hm.keyset (); Iterator<Student> it =Keyset.iterator ();  while(It.hasnext ()) {Student Stu=It.next (); String Addr=Hm.get (STU); System.out.println (Stu+".." +addr); }        //The second method of removal EntrySetSet<map.entry<student,string>> EntrySet =Hm.entryset (); Iterator<Map.Entry<Student,String>> iter =Entryset.iterator ();  while(Iter.hasnext ()) {Map.entry<Student,String> me =Iter.next (); Student Stu=Me.getkey (); String Addr=Me.getvalue (); System.out.println (Stu+"........."+addr); }    }}

tips for using collections:

1, see array is the structure of arrays, there is a corner mark, query speed quickly.

2, see link is linked list structure:

The deletion speed is fast, and has the unique method:

AddFirst; addlast; Removefirst (); Removelast (); GetFirst (); GetLast ();

3, see Hash is a hash table, you want to hash value, it is necessary to think of uniqueness, it is necessary to think of the elements deposited into the structure must cover hashcode (), Equals () method.

4, see tree is a binary tree, it is necessary to think of sorting and comparison.

two ways to compare:  

one is comparable : Overwrite CompareTo method;  

one is Comparator : Overwrite Compare method.

Linkedhashset,linkedhashmap: These two sets ensure that the hash table is stored in the order and in the order in which it is fetched.

when does the collection work?  

When storing an element, use collection. The map collection is used when there is a mapping between the stored objects.

Guaranteed to be unique, use set. Not guaranteed to be unique, use list.

Dark Horse Programmer------Java Collection Framework Learning Summary

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.