Java Collection and framework summary and learning

Source: Internet
Author: User
Tags new set set set

 Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka
This article will mainly explain the use of the collection in Java and the difference, mainly on the list, Set, map of the principle, the use of methods, precautions and so on.
first, the difference between collection and CollectonsJava Collection Framework is an important part of the Java language, it contains a system and a complete set of hierarchical system, encapsulating a large number of data structure implementation. A deep understanding of the composition structure of the Java Collection framework and its implementation classes and algorithms can greatly improve the programmer's ability to encode. This chapter describes the Java collection framework, which mainly includes the concept of the collection framework, the collection framework interface, and the list, collection, mapping three structures and iterative methods, comparison methods, and earlier versions of classes and interfaces. Let's learn these things together. A collection, sometimes called a container, is simply an object that aggregates multiple elements of the same nature into a single whole. A collection is used to store, fetch, manipulate, and transmit aggregated data. The Java Collection Framework provides efficient data structures and algorithms, so programmers do not need to write their own code to implement these functions. And the implementation of the interface is interchangeable, so it's easy to switch interfaces. This improves the reusability of the software.
Precautions :

(1) collection is a top-level interface of the collection class, and its direct inheritance interface has list and set

(2) Collections is a tool class/helper class for the collection Class , which provides a series of static methods for sorting, searching, and line Cheng of elements in the collection.

second, List, set, map three large sets of differences and explanationsThe Java platform provides a new set of frameworks. The core interfaces of the collection framework are collection, list (lists), set (set), and map (map).

Figure 1 Collection diagramAs you can see from Figure 1, collection is the topmost interface in the collection inheritance tree, and almost all Java Collection framework members inherit the collection interface or have a close relationship with it. Collection provides general operations on collections. Both the set interface and the list interface inherit the collection interface, and the map interface does not inherit the collection interface. Therefore, both the set object and the list object can invoke the method of the collection interface, and the map object cannot.     Here we explain the structure of the three types of interfaces: set is somewhat similar to the definition of a set in mathematics, and is a collection of unordered, non-repeating items. The list is a positional set, and the elements added to the list can be added to a specific position in the list or added to the end, saving duplicate elements. Map is used for keyword/value pairs, where keywords are unique identifiers of numeric values (non-repeatable), users can access data by keyword, and data can be duplicated. The specific Form 2 shows:
 Figure 2 Example of each collection element storage

(1) Collection: The root interface in the collection hierarchy, the JDK does not provide a direct implementation class for this interface.

(2) Set: cannot contain duplicate elements.

(3) List: is an ordered set of elements that can contain duplicates. Provides a way to access by index.

(4) Map: Contains the key-value pair. The MAP cannot contain duplicate keys.


iii. Summary of list usage3.1 List Interface

The main feature of the list is that its elements are stored in advance, allowing duplicate objects to be stored in the collection. The main implementation classes of the list interface are:

(1) ArrayList: Represents a variable-length array. Allows fast random access to elements, but it is slower to insert and delete elements into ArrayList.

(2) LinkedList: A linked list data structure is used in the implementation, and the elements are double links. Sequential access is optimized to insert and delete elements in the list faster, random access is relatively slow, random access refers to retrieving the elements at a particular index location, and LinkedList becomes the best choice in the list when quick insertions and deletions are required.

(3) Vector: is a thread-safe version of ArrayList, performance is lower than ArrayList, and is now rarely used.


3.2 ArrayList usage

3.2.1, ArrayList It's a collection .

       set can add things to the inside, with add (e E) method Add (put e object )

      Example: Span lang= "en-US" style= "word-wrap:normal; Word-break:normal ">arraylist add and get method ( add method to add data to the collection, get

(1) size () Method that returns the number of elements in the collection, similar to those in the array. length Properties

(2) Clear () Method To clear all the elements in the collection

      (3) isEmpty () method true

      (4) Remove (int index) Span style= "word-wrap:normal; The Word-break:normal "> method is to delete the element at the specified position in the collection, clearing the principle that after you clear the first one, the following elements move forward, the first variable 0 Oh, the third element is gone.

(5) Remove (Object ob) is a Remove , one is deleted according to the index, and one is deleted according to the specific object, such as Remove ("Hello");

(6) indexOf (obejct ob) determines the location of an element at the first position of the index.

View the number of array elements in the array, using the array's length property to view the number of collection elements in the collection, using the collection's size () method.


3.2.2, ArrayList use example

Import Java.awt.list;import java.util.arraylist;import java.util.iterator;/** * @author Lin Bingwen * @time 2015/2/5 * ArrayList with Method Example Description * */public class Main {public static void main (string[] args) {//arraylist Usage example arraylist<string> m_arraylist=n EW arraylist<string> (); M_arraylist.add ("Evankaka"); M_arraylist.add ("Lin Bingwen"); M_arraylist.add ("Lourdes"); m_ Arraylist.add ("Evankaka"); M_arraylist.add ("Little Red"); M_arraylist.set (2, "Wenbinglin");//Modify the object with index position 2 m_arraylist.add (3, "Xiu Xiu") ;//Add the object to the position at index 3//arraylist traversal method 1iterator<string> it_arraylist = M_arraylist.iterator (); SYSTEM.OUT.PRINTLN ("ArrayList traversal Method 1"), while (It_arraylist.hasnext ()) {System.out.println (It_arraylist.next ());} ArrayList Traversal Method 2system.out.println ("ArrayList Traversal Method 2"); for (Object o:m_arraylist) {System.out.println (o);} ArrayList Traversal Method 2system.out.println ("ArrayList traversal Method 3"), for (int i = 0; I<m_arraylist.size (); i++) { System.out.println (M_arraylist.get (i)); Delete element M_arraylist.remove ("Evankaka"); it_arraylist = M_arraylist.iterator (); System.out.println ("ARraylist after deleting an element "), while (It_arraylist.hasnext ()) {String m_string=it_arraylist.next (); if (M_string.equals (" Xiu Xiu ")) { It_arraylist.remove ();  }else{system.out.println (m_string); }}}}

Output Result:

ArrayList Traversal Method 1
Evankaka
Lin Bingwen
Wenbinglin
Show Show
Evankaka
Little Red
ArrayList Traversal Method 2
Evankaka
Lin Bingwen
Wenbinglin
Show Show
Evankaka
Little Red
ArrayList Traversal Method 3
Evankaka
Lin Bingwen
Wenbinglin
Show Show
Evankaka
Little Red
ArrayList traversal after deleting an element
Lin Bingwen
Wenbinglin
Evankaka
Little Red

3.2.3, ArrayList note

(1) The collection element cannot be modified while using iterator iteration, otherwise an exception is thrown. And iterator can only iterate backwards

(2) If you want to remove an element in the loop process, you can only call the It.remove method, you cannot use the List.remove method, or you must have a concurrent access error.

3.3 LinkedList Usage

The LinkedList class is the implementation of the various operations of the linked list node, and the LinkedList class implements a general-purpose doubly linked list with a tail-up reference. Note that this implementation is not synchronous. If multiple threads access the list at the same time, and at least one of the threads modifies the list from the fabric, it must remain externally synchronized. (A structural modification is any action that adds or removes one or more elements; The value of the set element is not a structural modification.) This is typically done by synchronizing the objects that naturally encapsulate the list. If such an object does not exist, you should use the Collections.synchronizedlist method to "wrap" the list. It is a good idea to do this at creation time to prevent accidental, out-of-sync access to the list.


four, set interface

There is no obvious order between multiple objects in the set collection, and the set is essentially the same as the collection structure, except that the set cannot contain duplicate elements. The set determines that two objects are the same, not using the = = operator, but according to the Equals method. This means that the main two objects that are returned True,set with the Equals method will not accept the two objects. HashSet is a typical implementation of the set interface, and most of the time using a set set is using this class.

4.1 HashSet Description and Example

The

      HashSet stores the elements in the collection by the hash algorithm, so it has good storage and lookup performance. &NBSP;
       cannot guarantee the order of the elements, the order may change  
     hashset is not synchronous, if multiple threads access the same hashset, be aware of thread safety issues  
      set element value can be null 
      when an element is deposited into the HashSet collection, HashSet invokes the hashcode () of the object method to get the Hashcode value of the object and then determine where the object is stored in hashset based on that value. If there are two elements that return true through the Equals method, but their Hashcode method return values are not equal, HashSet will store them in a different location. That is, the HashSet set determines that two elements are equal by two objects that are equal by the Equals method, and that the return values of the hashcode methods of two objects are equal.

Examples of Use:

Package Com.collection;import Java.util.date;import Java.util.hashset;import java.util.iterator;public class Main{ Public    static void Main (String [] args)    {       HashSet h=new HashSet ();       H.add ("1st");       H.add ("2nd");       H.add (New Integer (3));       H.add (new Double (4.0));       H.add ("2nd");            Duplicate element, not added       H.add (new Integer (3));      Duplicate element, not added       H.add (new Date ());       System.out.println ("Start: Size=" +h.size ());       Iterator it=h.iterator ();       while (It.hasnext ())       {           Object o=it.next ();           System.out.println (o);       }       H.remove ("2nd");       System.out.println ("After removing elements: size=" +h.size ());       System.out.println (h);    }}
Results:

Start: size=5
4.0
1st
3
2nd
Mon Feb 20:52:17 CST 2015
After removing an element: size=4
[4.0, 1st, 3, Mon Feb 20:52:17 CST 2015]

4.2 TreeSet

TreeSet describes a variant of set-a collection of functions such as sorting, which is automatically inserted into an ordered sequence of objects by a comparison rule when the object element is added to the collection, and guarantees that the set elements are organized in ascending order.

Examples of Use:

Package Com.collection;import Java.util.treeset;import Java.util.iterator;public class main{public    static void Main (String [] args)    {       TreeSet ts=new TreeSet ();       Ts.add ("Orange");       Ts.add ("Apple");       Ts.add ("banana");       Ts.add ("Grape");       Iterator it=ts.iterator ();       while (It.hasnext ())       {           string fruit= (String) it.next ();           SYSTEM.OUT.PRINTLN (fruit);}}}    

Results:

Apple
Banana
Grape
Orange

4.3 Set summary     (1) HashSet and TreeSet are the two typical implementations of set. hashset performance is always better than treeset (especially common additions, queries, etc.) because TreeSet requires additional red-black tree algorithms to maintain the order of the collection elements. You should use TreeSet only if you need a set that holds the sort, otherwise you should use HashSet.
      (2)   Linkedhashset is a subclass of HashSet, which also determines where an element is stored, based on the hashcode value of the element. But it also maintains the order of elements using a list of links, so that the elements appear to be saved in the order in which they are inserted. linkedhashset need to maintain the insertion order of the elements, so performance is slightly lower than hashset performance, but will have good performance when iterating through all the elements in the set,
(3) TreeSet is an implementation of the SortedSet interface, TreeSet ensures that the collection elements are in the sorted state, and TreeSet is not sorted according to the order in which the elements are inserted, but by the actual values of the elements.
(4) Enumset is the best performance in any set implementation class, but it can only hold an enumeration value of the same enumeration class as a collection element.
(5) It must be noted that the set of three implementation classes HashSet, TreeSet, and enumset are thread insecure, if there are multiple threads accessing a set collection at the same time, and more than one thread has modified the set collection, you must manually guarantee the synchronization of the set set. The set collection can usually be wrapped by the Synchronizedsortedset method of the Collections tool class. This is best done at creation time.

Five Map Interface

To be Continued ~


Java Collection and framework summary and learning

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.