Java Learning Notes (16)

Source: Internet
Author: User
Tags set set

List interface

Check out the API to see the list's introduction. An ordered collection (also known as a sequence). Users of this interface can precisely control the insertion position of each element in the list. The user can access the element based on the integer index of the element (where it is located in the list) and search for the elements in the list. Unlike set, a list usually allows repeating elements.

List interface:

It is a collection of elements that are accessed in an orderly manner. For example, the order in which elements are stored is 11, 22, 33. In the collection, the storage of the elements is done in the order of 11, 22, and 33.

It is a collection of indexes that can be used to manipulate the elements in the collection precisely (as with the index of an array).

The collection can have duplicate elements, through the Equals method of the element, to compare whether it is a repeating element.

The common subclasses of the list interface are: ArrayList collection, LinkedList collection

Common methods in the list interface
 Public Static voidMain (string[] args) {//Add (); //Delete (); //update (); //get ();edit (); }    /** void Add (int index,e Element) * Add element in the specified position * java.lang.IndexOutOfBoundsException the bounds of the collection of the exception * Java.lang . ArrayIndexOutOfBoundsException array out-of-bounds exception * Java.lang.StringIndexOutOfBoundsException string out-of-bounds exception **/     Public Static voidAdd () {List<String> list=NewArraylist<string>(); List.add ("ABC"); List.add ("456"); List.add ("BCD"); List.add (3, "RRR");    SYSTEM.OUT.PRINTLN (list); }    /** E Remove (int index) * 1. Delete the element at the specified position * 2. Returns the value of this element **/     Public Static voidDelete () {List<String> list=NewArraylist<string>(); List.add ("ABC"); List.add ("456"); List.add ("BCD"); List.add (3, "RRR");        SYSTEM.OUT.PRINTLN (list); String element=list.remove (0);        SYSTEM.OUT.PRINTLN (Element);    SYSTEM.OUT.PRINTLN (list); }    /**e Set (int index,e Element) * * Replace the value at the specified position. You can also get the replacement previous value **/     Public Static voidUpdate () {List<String> list=NewArraylist<string>(); List.add ("ABC"); List.add ("456"); List.add ("BCD");        SYSTEM.OUT.PRINTLN (list); String e=list.set (1, "Daniel Wu");        System.out.println (e);    SYSTEM.OUT.PRINTLN (list); }    /** E get (int index) * Gets the element value on the specified index **/     Public Static voidget () {List<String> list=NewArraylist<string>(); List.add ("ABC"); List.add ("456"); List.add ("BCD");        SYSTEM.OUT.PRINTLN (list); System.out.println (List.get (0));  for(intI=0;i<list.size (); i++) {System.out.println (List.get (i)); }    }
Concurrency modification exceptions for iterator
 /** Iterator Concurrency Modification exception * In the process of traversal, only do not change the length of the thing * once you do change the length of things, there will be a concurrent modification exception **/     Public Static voidedit () {List<String> list=NewArraylist<string>(); List.add ("ABC"); List.add ("456"); List.add ("BCD"); Iterator<String> it=List.iterator ();  while(It.hasnext ()) {String str=It.next ();            System.out.println (str); if(Str.equals ("456")) {                intI=list.indexof (str); List.set (i,"Daniel Wu");        } System.out.println (str); }
The structure of the list collection to store data

There are a number of collections under the list interface, and the structure in which they are stored is different, resulting in these sets having their own characteristics that can be used in different contexts. The common structures of data storage are: Stacks, queues, arrays, linked lists.

Stack, using the structure of the collection, the access to the element is like the following characteristics:

Advanced-out (that is, the element to be stored in, to be removed after the element after it in turn to remove the element). For example, a bullet is pressed into a magazine, a bullet that is pressed into it, a bullet in the back, a shot in the top, and a bullet that pops up before it pops up.

The entry and exit of the stack is the top position of the stack.

Stack: The element is stored. That is, the elements are stored at the top of the stack, and the elements in the stack move one position to the bottom of the stack in turn.

Stack: Just take the element. That is, the top position of the stack element is taken out, the stack of elements in turn to the top of the stack to move a position.

Queue, using the structure of the collection, the access to the element is like the following characteristics:

FIFO (that is, the element that is stored in, to be removed after the element in front of it, before the element can be taken out). For example, security. In a row, each person checks in turn, only the front of the people to complete the inspection, before the current people to check.

Each side of the queue's entrance and exit. For example, the left side of the entry is the entrance and the right is the exit.

Array, using the set of the structure, the access to the element has the following characteristics:

Find elements fast: Through the index, you can quickly access the elements at the specified location

Adding or deleting elements is slow:

add element at the specified index: you need to create a new array, store the specified new element at the specified index, and then copy the original array elements to the new array's corresponding index, based on the index. Such as

Delete element at the specified index location: A new array needs to be created, and the original array elements are copied to the position of the new array corresponding to the index, and the specified index position elements in the original array are not copied to the new array.

Linked list, using the structure of the collection, the access to the element is like the following characteristics:

Between multiple nodes, connect through an address. For example, many people hold hands, everyone uses their right hand to pull down a person's left hand, and so on, so many people are connected together.

Find elements slow: To find an element, you need to go through the connected node, looking back to the specified element

Delete elements quickly:

Add element: Operation as shown on the left, just modify the address of the next element to be connected.

Delete element: The action, as shown on the right, simply modifies the address of the next element to be connected.

ArrayList Collection

The structure of the ArrayList collection data store is the array structure. Elements are slow to delete, Find Fast, because the most used features in daily development for querying data, traversing data, so ArrayList is the most common collection.

LinkedList Collection

The structure of the LinkedList collection data store is the linked list structure. A collection of convenient elements to add and delete. Here are the common methods of LinkedList

 Public Static voidMain (string[] args) {//Add ();get (); }/** void AddFirst (e e) Inserts the specified element at the beginning of this list * Coid AddLast (e e) Inserts the specified element at the end of this list * **/     Public Static voidAdd () {LinkedList<String> list=NewLinkedlist<string>(); List.addlast ("Cheng, Chen"); List.add ("Daniel Wu"); List.addfirst ("Tony Leung");    SYSTEM.OUT.PRINTLN (list); }    /** e GetFirst () returns the first element of this list * e GetLast () returns the last element of this list * java.util.NoSuchElementException * */     Public Static voidget () {LinkedList<String> list=NewLinkedlist<string>(); List.addlast ("Cheng, Chen"); List.add ("Daniel Wu"); List.addfirst ("Tony Leung"); String F=List.getfirst (); String L=List.getlast (); System.out.println (f+l); }}
Vector Collection

The structure of the vector collection data store is the array structure, which is the oldest provided collection in the JDK. The vector provides a unique way to take out, which is to enumerate enumeration, which is actually an early iterator. The functionality of this interface enumeration is similar to the functionality of the Iterator interface. The vector collection has been replaced by ArrayList.

Comparison of vector sets with ArrayList collection:

Set interface

List and set 10 collection two sub-interfaces, before we know that the list can hold repeating elements. The collection inside the set interface stores the elements that are not duplicates. By looking at the API of the set set, it is determined by the Equals method that the set set determines whether the element is duplicated.

HashSet Collection

  Refer to the API for HashSet collection: This class implements the set interface, which is supported by a hash table (actually a HashMap collection). The HashSet collection cannot guarantee that the sequence of iterations is the same as the order in which the elements are stored. The HashSet collection, which stores the data in a hash table structure, guarantees that the element uniqueness depends on: the Hashcode () and the Equals () method.

HashSet The structure (hash table) of the collection store data

What is a hash table?

The bottom of the hash table is also the array mechanism, the array also holds the object, and these objects are placed in the array in the location of the special, when the need to put these objects to the array, then according to the specific data of these objects combined with the corresponding algorithm, the object in the array to calculate the position, and then put this object in the array. And such an array is called a hash array, that is, a hash table.

When storing elements in a hash table, it is necessary to combine the corresponding algorithm according to the unique data of the element, which is actually the Hashcode method in the object class. Because any object is a subclass of the object class, any object has this method. That is, when the object is stored in the hash table, it calls the object's Hashcode method, calculates where the object is stored in the table, it is important to note that if the two object Hashcode method calculates the result, this phenomenon is called the hash conflict, then the object's Equals method is called. Comparing the two objects is not the same object, if the Equals method returns True, then the second object will not be stored in the hash table, if the return is false, this value will be stored in the hash table.

ImportJava.util.HashSet;/** 1. Computes the hash value of the stored object and compares it to the same hash value in the collection * 2. If you have the same hash value, then call the Equals method, "AaB". Equals ("AaB"), if the same * returns TRUE, to determine that this is a repeating element, discard * 3. If the hash value is the same, the Equals method is called, and if Euqals returns FALSE, it is stored in set * **/ Public classHashsetdemo { Public Static voidMain (string[] args) {method (); }     Public Static voidmethod () {HashSet<Person> hs=NewHashset<person>(); Person P1=NewPerson ("a", 12); Person P2=NewPerson ("B", 11); Person P3=NewPerson ("B", 11); Person P4=NewPerson ("D", 12);                System.out.println (P1.hashcode ());                System.out.println (P2.hashcode ());                System.out.println (P3.hashcode ());                Hs.add (p1);                Hs.add (p2);                Hs.add (p3);                Hs.add (p4);    SYSTEM.OUT.PRINTLN (HS); }     Public Static voidHash () {HashSet<String> hs=NewHashset<string>(); Hs.add ("AaB"); Hs.add ("AaB"); Hs.add ("BBC"); Hs.add ("BBC");    SYSTEM.OUT.PRINTLN (HS); }}

When you store the type elements provided in Javaapi in HashSet, you do not need to override the hashcode and equals methods of the elements, because both methods have been rewritten in each of the JAVAAPI classes, such as the String class, the integer class, and so on.

  When you store a custom type element in HashSet, you need to override the hashcode and Equals methods in the object to establish your own comparison to ensure that the objects in the HashSet collection are unique.

Linkedhashset

Under HashSet there is a subclass Linkedhashset, which is a data storage structure for the combination of linked lists and hash tables. The difference between it and HashSet is that the Linkedhashset set guarantees the order in which the elements are deposited and taken out.

Java Learning Notes (16)

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.