Java container learning notes (I) Basic concepts and collection interface knowledge of containers

Source: Internet
Author: User
Tags addall

This article mainly summarizes the knowledge points in Java containers, including the container hierarchy, class graph structure, and collection Interface Details, and a collection sub-interface list Interface related knowledge point summary. It involves learning and summarizing the underlying data structures, implementation mechanisms, and usage of some classes such as arraylist, javaslist, vector, stack, and copyonwritearraylist.

 

I. Basic Concepts

Java container class library is used to save objects. It is divided into two different concepts based on different data structures.

(1) Collection, a sequence of independent elements. The list stores elements in the element insertion order, while the set does not have repeated elements. The queue follows FIFO) the stack manages data in the order of first-in-first-out (LIFO.

(2) map, a sequence of key-value pairs (key-value) objects. You can use the key to find the value, where the key cannot be repeated, and the value can be repeated. We can call it a dictionary or an associated array. Hashmap is unordered, treemap is ordered, weakhashmap is weak, and hashtable is thread-safe.

The figure below is from Chapter 17th of thinking in Java fourth edition:

In addition to the content shown in the figure above, a large number of thread-safe collection classes are also implemented in the Java. util. Concurrent package for convenient use. Such as concurrenthashmap, copyonwritearraylist, and copyonwritearrayset.

Ii. Collection Interface

The Collection class graph structure shows that the collection interface is the most basic set interface in Java, and the specific implementation class of the collection interface is not directly provided in JDK, the collection function implementation class is mainly for its two more specific sub-interfaces list and set specific implementation class. However, the collection interface defines a set of general operation implementation methods and naming rules.

The collection interface, subinterfaces, and implementation classes can be viewed in the JDK help document.

Ø there are at least two methods to construct the implementation class of the collection interface: one is the void (No parameter) constructor, which is used to create an empty collection object instance; the other is a constructor with a collection type parameter to create a collection object instance with the same elements as its parameters. For example, the construction methods of the hashset class are as follows:

A) hashset (): constructs an Instance Object of the hashset class with an initial capacity of 16 and a load factor of 0.75;

B) hashset (collection <? Extends E> C): constructs an object instance of the hashset class containing the specified set object.

C) hashset (INT initialcapacity): constructs an Instance Object of the hashset class with a specified initial capacity.

D) hashset (INT initialcapacity, float loadfactor): constructs an Instance Object of the hashset class with the specified initial capacity and loading factor.

The collection interface defines 15 common methods:

A) List of collection interface methods

A) add or delete an element in the Set

• Boolean add (e o): append the specified element to the set.

• Boolean remove (Object O): removes the specified element from the set.

B) query collection-related data

• Int size (): returns the number of elements in the set.

• Boolean isempty (): test whether the set is empty.

• Boolean contains (object element): test whether the element exists in this set.

• Iterator <E> iterator (): The iterator that returns each element in the set for iteration.

C) operate on several elements in groups

• Boolean containsall (collection <?> C): determines whether the set contains a given group of elements. If the set contains, true is returned. Otherwise, false is returned.

• Boolean addall (collection <? Extends E> C): Adds all elements in the specified set to the current set.

• Void clear (): removes all elements from this set.

• Boolean removeall (collection <?> C): remove the elements in the set that are also included in the specified set (evaluate the difference set of the set)

• Boolean retainall (collection <?> C): only the elements in the set that are also included in the specified set are retained (intersection of the set)

D) convert the set to an object array.

• Object [] toarray (): returns an array containing all elements in the collection.

• <T> T [] toarray (T [] A): returns an array containing all elements in the set. returns the runtime type of the array, which is the same as the runtime type of the specified array.

 

1. List interface and its implementation class


List of methods in the list Interface

A list can maintain elements in a specific sequence and allow multiple occurrences of the same element in the set. The list interface adds a large number of methods to the collection interface, allowing you to insert and remove elements in the list. In addition to abstract classes, arraylist (implemented based on arrays), sorted list (implemented based on cyclic linked lists), vector (implemented based on arrays, thread security ), stack (a subclass of vector, implemented based on arrays) and copyonwritearraylist (implemented based on arrays and thread security)

Various location-oriented operations methods provided in the list interface: (the existing methods in the set are omitted)

• Void add (INT index, e element): Insert a specified element at a specified position in the list.

• Boolean addall (INT index, collection <? Extends E> C): inserts all elements in the specified set into the specified position in the set.

• E get (INT index): returns the elements at the specified position in the set.

• Int indexof (Object O): returns the index that appears for the first time of the specified object in the collection. The returned value-1 indicates that this element does not exist starting from 0.

• Int lastindexof (Object O): returns the last index position of the specified object in the set. The returned value-1 indicates that the index does not exist.

• Listiterator <E> listiterator (): returns the list iterator of elements in the set in the correct order.

• Listiterator <E> listiterator (INT index): returns the list iterator of elements in the set in the correct order, starting from the specified position in the set.

• E remove (INT index): removes the elements at the specified position in the set.

• E set (INT index, e element): replaces the element at the specified position in the set with the specified element.

• List <E> sublist (INT fromindex, int toindex): Return partial views between the specified fromindex (inclusive) and toindex (excluded) in the set.

The list interface provides a special iterator named listiterator.

Lists are represented in arrays, vectors, linked lists, stacks, queues, and other forms in the data structure.

ØFeatures, implementation mechanism, and usage of arraylist

A) features of arraylist:

As the name implies, arraylist is a linear table implemented by arrays. Regular arrays do not have the auto increment function, but we do not need to consider this issue when using arraylist. You can index data directly by location. The search and modification speed is fast, but the insertion or deletion speed is slow. The system. arraycopy method is called when inserting and deleting data. It is an native method.

B) Implementation Mechanism of arraylist:

In the JDK source code, we can see that arraylist has only two attributes, one is elementdata of the object array type and the other is the size of the int type.

In the constructor, we can also see that the non-argument constructor calls this (10). The constructor that calls a constructor with a parameter, by default, no parameter constructor assigns an array with a size of 10. According to the constructor defined in the collection interface, it must have a method to construct its own object through other collection objects. This is a relatively simple linear table. In addition, JDK provides a large number of easy-to-use methods. When the storage space is insufficient, use the following method to reallocate the dynamic array:

Newcapacity = (oldcapacity * 3)/2 + 1;

If (newcapacity <mincapacity) newcapacity = mincapacity;

C) usage (arraylist is actually relatively simple to use, but it is also relatively common and easy to use, personal feeling)

The following example may seem meaningless to use the arraylist method as much as possible.

Import Java. util. arraylist; import Java. util. iterator; import Java. util. list; public class exampleforarraylist {public static void main (string [] ARGs) {string [] STR = new string [] {"my", "name", "is ", "Wang", "Yan", "Tao"}; List <string> LS1 = new arraylist <string> (10 ); // Add the data in the array to LS1 for (INT I = 0; I <Str. length; I ++) {ls1.add (STR [I]) ;}// use LS1 to construct ls2list <string> ls2 = new arraylist <string> (LS1); system. out. println ("number of elements in ls2:" + ls2.size (); system. out. println ("is location in ls2:" + ls2.indexof ("is"); system. out. println ("the last location of Wang in ls2:" + ls2.lastindexof ("Wang"); system. out. println ("all elements in ls2:"); // here iterator is used to traverse iterator <string> it = ls2.listiterator (); While (it. hasnext () {system. out. println (it. next ();} // I usually use the following method to traverse, or the basic for loop traversal for (string TMP: ls2) {system. out. println (TMP );}}}

ØShortlistFeatures, implementation mechanisms, and usage

A) features of tranquility list:

It is found that the class name in Java is really good. For example, you can see that it is implemented using a linked list. The advantage of the linked list operation is that the insert/delete operation is relatively fast, but it cannot be directly accessed by index. Therefore, the update operation is relatively fast and the query operation is relatively slow. Its overall feature is caused by arraylist.

B) Implementation Mechanism of consumer list:

View the JDK source code to find that each element is an instance object of listing list. Entry in listing list. This class is defined as follows:

private static class Entry<E> {E element;Entry<E> next;Entry<E> previous;Entry(E element, Entry<E> next, Entry<E> previous) {    this.element = element;    this.next = next;    this.previous = previous;}}

In the constructor, this definition is as follows:

Header. Next = header. Previous = header;

That is to say, the underlying layer of the consumer list is implemented using a circular bidirectional linked list.

The revoke List implements many operations on the first and last elements, such as set, get, and remove.

Although the retrieve list method is slower to obtain the elements at the specified position than the arraylist method by index, the get method is optimized in JDK:

       if (index < (size >> 1)) {            for (int i = 0; i <= index; i++)                e = e.next;       } else {            for (int i = size; i > index; i--)                e = e.previous;       }

Although the search is sequential, it has been optimized. Size> 1 = size/2, the shift operation is much more efficient than the division operation.

C) the usage of the rule list is similar to that of the arraylist, but it depends on your needs. In addition, the stack list also implements all stack operations.

ØFeatures, implementation mechanisms, and usage of Vector

A) features of vector:

Arraylist implements a dynamic array, and the sorted list is a two-way circular linked list. Vector does not implement the first two, but directly implements the list interface. All the methods in vector are preceded by a synchronized keyword. The vector is ordered and repeatable.

B) Implementation Mechanism of vector:

I still don't understand why we need to implement the Vector class, which is basically the same as that of arraylist. What's different is that the vector is thread-safe, however, collections provides a way to convert a non-thread-safe set into a thread-safe set.

C) How to Use Vector (similar to how to use arraylist)

ØFeatures, implementation mechanisms, and usage of stack

A) features of Stack:

Stack is a sequence of first-in-first-out operations, such as empty identification, stack pressure, stack rollback, and top-off Stack elements.

B) Implementation Mechanism of Stack:

Stack inherits from the vector and uses arrays to store data. The restriction operation is performed based on the characteristics of the data structure. JDK provides six methods for specific operations:

• Stack (): Construct an empty Stack

• Empty (): determines whether the stack is empty.

• PEEK (): view the top element of the stack and return the top object of the stack.

• POP (): deletes the stack top element and returns the stack top object.

• Push (E element): pushes an element to the current stack.

• Search (Object O): Check whether the specified object is in the current stack.

C) stack usage

Import Java. util. stack; public class exampleforstack {/** this is a very simple example * used to display the post-first-out feature of the stack * print a string in reverse order */public static void main (string [] ARGs) {string STR = "abcdefghijklmnopqrstuvwxyz"; stack <character> stack = new stack <character> (); For (char CH: Str. tochararray () {stack. push (CH) ;}while (! Stack. Empty () {system. Out. Print (stack. Pop ());}}}

ØFeatures, implementation mechanism and usage of copyonwritearraylist

A) features of copyonwritearraylist:

Copyonwritearraylist is a class in the Java. util. Concurrent package. This class is a thread security class. Because reentrantlock is used for synchronization, the modification efficiency is lower than that of arraylist.

B) Implementation Mechanism of copyonwritearraylist:

At first, I thought the name was long and strange. Why should I name it like this? First of all, this is a class designed to achieve concurrent synchronization, so lock will be used in all aspects related to the modification method to ensure synchronization. The English meaning of copy-on-write is "Copy at write and copy at write". Now it seems that this name is easier to understand. How is this class implemented? The interviewer said: "Look at the source code in a down-to-earth manner ". -_-|

First, let's talk about the writing method:

• Public e set (INT index, e element): replace the element at the specified position with the element. The source code in JDK is as follows:

public E set(int index, E element) {final ReentrantLock lock = this.lock;lock.lock();try {Object[] elements = getArray();Object oldValue = elements[index];if (oldValue != element) {int len = elements.length;Object[] newElements = Arrays.copyOf(elements, len);newElements[index] = element;setArray(newElements);} else {setArray(elements);}return (E)oldValue;} finally {lock.unlock();}}

From the source code, we can see that when you first perform the write (including set, add, remove, and so on) operation, you first get the re-entry lock of the current object, next, get a copy of the current object element (copy at write time), replace the original element with the modified element again, and finally release the lock.

Two common sense examples are provided here:

1. in Java, the "=" operation only associates a reference with an object. If a thread points a reference to another object, a thread obtains the object pointed to by the reference, so there will be no concurrentmodificationexception between them. They are blocked at the virtual machine level, and the speed is very fast and almost no CPU time is required.

2. Two different references in Java point to the same object. When the first reference points to another object, the second reference will keep the original object.

• Public void add (E): Add a specified element to the current object. The implementation method is the same as set, which is copy-on-write.

• You can also perform operations such as remove to modify the content.

In addition to the write method (modify, delete, and add), The copyonwritearraylist class also provides methods similar to the arraylist and more fully functional.

• Public listiterator <E> listiterator (): This method returns an iterator of the listiterator type, but the real type of the iterator is of the cowiterator type, insertion, deletion, and addition methods are not allowed.

The usage is similar to that of arraylist, but it is only a matter of selection. Because the system. arraycopy method is widely used in write operations, the efficiency will be reduced. Therefore, it is suitable for scenarios where read operations are much larger than write operations.

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.