Java Collection Class Basics (List,set,map) __java

Source: Internet
Author: User
Introduction to collection classes

The Java Collection class derives primarily from two interfaces:collection and Map, which also contain some interfaces or implementation classes.
A collection represents a set of object, the collection element (Elements). Some collection allow the same elements while others do not. Some can be sorted and others not. The Java SDK does not provide a direct implementation of collection, and provides classes that inherit from collection such as list and set. so set, list, and map can be seen as three parts of a set .

Collections is a Help class for a collection framework that contains some sort of collection, search, and serialization operations.

The advantages of the collection framework are as follows:
(1) Use core collection classes to reduce development costs rather than implementing our own collection classes.
(2) with the use of rigorously tested collection framework classes, code quality can be improved.
(3) The cost of code maintenance can be reduced by using the collection classes that are included with the JDK.
(4) reusability and operability.

Benefits of using generics .
(1) Generics allow us to provide a type of object that can be accommodated for the collection, so if you add any other type of element, it will be wrong in the compile times. This avoids classcastexception at run time, because you will get an error message at compile time.
(2) Generics also make the code neat, and we don't need to use explicit conversions and instanceof operators.
(3) It also brings benefits to the runtime, since byte-code directives that do not produce type checks are generated. ways to traverse a collection: iterator interface and foreach Loop

Collection has an important approach: iterator (), which returns an iterator iterator that traverses all the elements of the collection. The iterator model can abstract the access logic from different collection classes, thus avoiding exposing the internal structure of the collection to the client.

The specific types of iterator that each collection class returns may be different, but they all implement the iterator interface, so we don't need to care what kind of iterator it is, it just needs to get the iterator interface, which is the benefit of the interface, the power of the object-oriented.

The iterator replaces the enumeration (Legacy Class) In the Java Collection framework, and iterator is more secure because when a collection is being traversed, it prevents other threads from modifying the collection (in a way that throws an exception). To ensure that the traversal process completes smoothly, you must ensure that the contents of the collection are not changed during traversal (except for the Remove () method of the iterator), so the principle of ensuring traversal is that it is used only in one thread, or that the traversal code is synchronized across multiple threads.

The iterator interface provides three ways:
(1) Boolean hasnext (): Returns the next element in the collection.
(2) Object next (): Returns the next element in the collection.
(3) void Remove (); Deletes the element returned by the previous next method in the collection.
Typical usage is as follows:

public class Testiterator {public 
    static void Main (string[] args) { 
        //Create a collection 
        Collection books = new HashSet () ; 
        Books.add ("Lightweight Java enterprise application of actual combat"); 
        Books.add ("Struts2 Authority Guide"); 
        Books.add ("Ajax treasure based on Java ee"); 
        Gets the iterator for the books collection 
        iterator<string> it = Books.iterator (); 
        while (It.hasnext ()) { 
            String book = It.next (); 
            SYSTEM.OUT.PRINTLN (book); 
            if (Book.equals ("Struts2 authoritative guide")) { 
                it.remove ();
                When using iterator iterations, the collection element cannot be modified, and the following code throws an exception
                //books.remove (book); 
            Assigning a value to a book variable does not change the collection element itself book 
            = "test string"; 
        } 
        SYSTEM.OUT.PRINTLN (books); 
    } 

Program Run Result:

Struts2 authoritative guide 
based on Java-EE AJAX book 
lightweight Java EE application of the actual combat 
[based on Java EE Ajax treasure, lightweight Java Enterprise Application of practical]

Description
(1) through the statement book = "test string"; When you assign a book to an iteration variable, when we output the books collection again, the elements in the collection do not change. That is, when using iterator to iterate over the collection elements, the iterator does not pass the collection element itself to the iteration variable, but instead passes the value of the collection element to the iteration variable. Because Java is a value delivery, see: The way Java parameters are passed.
(2) When using iterator to access collection collection elements, only the iterator Remove method can delete the current element. Other behavior that changes the contents of the collection during traversal throws a Java.util.ConcurrentModificationExcption exception.

In contrast, for each of the way the thread is unsafe, but simplifies the code, and does not have to be out of bounds. List Interface

The list is an ordered collection that can have the same elements, and this interface allows you to control exactly where each element is inserted. Users can access the elements in the list, similar to the Java array, by using the index (the position of the element in the list, similar to the array subscript).

In addition to the iterator () method with the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface, Listiterator adds some methods such as add (), allows adding, deleting, setting elements, and traversing previous () forward or backward.

Common classes that implement the list interface are Linkedlist,arraylist,vector and stack (the latter two are legacy classes). LinkedList class

LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides additional Get,remove,insert methods at LinkedList's header or tail. These operations enable LinkedList to be used as stacks (stack), queues (queue), or bidirectional queues (deque). Be good at frequently adding and deleting elements.

Note that LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list when the list is created:

List List = Collections.synchronizedlist (new LinkedList (...));
ArrayList class

ArrayList implements a variable sized array, allows null elements, and no synchronization methods. Be good at random access elements. Unlike array, array can hold basic types and objects, and ArrayList can only hold objects.

Each ArrayList instance has a capacity (Capacity), which is the size of the array used to store the elements. This capacity can automatically increase as new elements are added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to increase the insertion efficiency. vector classes and Stack classes

is deprecated as a legacy class. Vectors are very similar to ArrayList, both indexed, internally supported by an array, maintaining the insertion order. But vectors are synchronized.
Stack inherits from the vector, providing 5 additional methods: The basic push and pop methods, and the Peek method gets the top element of the stack, the empty method tests whether the stack is empty, and the search method detects the position of an element on the stack. set Interface

A set is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element.
Note: You must be careful to manipulate variable objects (mutable object). If a variable element in a set changes its state, causing the Object.Equals (Object) =true to cause some problems.

The set interface has the following implementations:
(1) HashSet: For quick Find design set, the main feature is: cannot hold duplicate elements, and the use of hashing storage method, so there is no order. There is no order in which the elements are inserted in a sequence that is inconsistent with the order of the output.
(2) TreeSet: Save order of Set, the bottom is the tree structure. Use it to extract ordered sequences from set.
(3) Linkedhashset: Has a hashset query speed, and the internal use of linked lists to maintain the order of elements (the order of insertion). So when you use iterators to traverse set, the results are displayed in the order in which the elements are inserted. Map Interface

Commonly used are HashMap, Linkedhashmap, Hashtable and TreeMap. For more information, please see:
Java8 HashMap Detailed (storage structure, function implementation, expansion optimization, thread safety, traversal method).
The main point here is that because the object of the key will be computed by its hash function to determine the location of the corresponding value, so any object as a key must implement the Hashcode and Equals method.
The hashcode and Equals methods inherit from the root class object, and if you use a custom class as a key, be very careful, as defined by the hash function, if two objects are the same, that is, Obj1.equals (OBJ2) =true, Their hashcode must be the same, but if two objects are different, their hashcode is not necessarily different, and if the hashcode of two different objects is the same, this phenomenon is called conflict, and the conflict causes the time overhead of manipulating the hash table, so as to define the hashcode () method to speed up the operation of the hash table.
If the same object has a different hashcode, the operation of the hash table will have unexpected results (the expected GET method returns null), to avoid this problem, you need to keep in mind one: to copy the equals method and the Hashcode method at the same time, not just write one of the . In fact, it is best to use the immutable class provided by JDK as the key of the map to avoid implementing hashcode () and Equals () yourself. Conclusion

The above is the collection framework related interface and class introduction, and finally note that, as far as possible to return the interface rather than the actual type, such as return list instead of ArrayList, so that if you need to replace ArrayList LinkedList, the client code does not have to change. This is for abstract programming.

Reference from: Large companies like to ask the Java Collection class face questions
Java Collection Framework Summary-super detail-Suitable for interview
40 Java set interview questions and answers

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.