Java Learning list interface, set interface

Source: Internet
Author: User
Tags repetition

The two most commonly used subclasses in collection (List collection, set collection)

List interface

1, it is an element of an orderly collection of access. The order here is not to say that the set is stored in ascending order, but rather how the elements are deposited and how they are taken out.

2, it is an indexed collection, through the index can be precise operation of the elements in the collection (and the index of the array is a reason).

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

Common subclasses of the list interface are:

1. ArrayList Collection

2. LinkedList Collection

Common methods in list:

Package Com.oracle.demo1;import Java.util.arraylist;import Java.util.iterator;import Java.util.list;public class        Listdemo {public static void main (string[] args) {add (); remove (); set (); Get (); Edit ();} /* * void Add (int index,e Element) add element * Java.lang.IndexOutOfBoundsException collection out of bounds exception in specified position * Java.lang.ArrayIndexOutOfBou Ndsexception array out of Bounds exception * Java.lang.StringIndexOutOfBoundsException string out of bounds exception */public static void Add () {list<string > list = new arraylist<string> (), List.add ("ASD"), List.add ("123"); List.add ("Zxc"); List.add (0, "xxx"); SYSTEM.OUT.PRINTLN (list);} /* * E Remove (int index) * 1, delete the element at the specified position * 2, return the value of the deleted element */public static void Remove () {list<string> List = new Arra Ylist<string> (), List.add ("ASD"), List.add ("123"), List.add ("Zxc"); String element = list.remove (0); SYSTEM.OUT.PRINTLN (Element); SYSTEM.OUT.PRINTLN (list);} /* * E set (int index,e Element) * 1, replace the value at the specified position * 2, get the value before replacing */public static void set () {list<string> List = new Arra Ylist<string> ();List.add ("ASD"); List.add ("123"); List.add ("Zxc"); SYSTEM.OUT.PRINTLN (list); String e = list.set (1, "John Doe"); System.out.println (e);} /* * E get (int index) * Gets the element value on the specified index * */public static void Get () {list<string> List = new arraylist<string> (); l Ist.add ("ASD"); List.add ("123"); List.add ("Zxc"); SYSTEM.OUT.PRINTLN (list); System.out.println (list.get (0)); for (int i=0;i<list.size (); i++) {System.out.println (List.get (i));} System.out.println ("================="); for (String e:list) {System.out.println (e);} System.out.println ("=================");iterator<string> it=list.iterator (); while (It.hasnext ()) { System.out.println (It.next ());}} /* * Iterator Concurrency Modification Exception * Java.util.ConcurrentModificationException * Cannot modify the length of the operation during traversal, otherwise the concurrency modification exception will occur * */public static void Ed It () {list<string> List = new arraylist<string> (), List.add ("ASD"), List.add ("123"), List.add ("Zxc"); Terator<string> It=list.iterator (), while (It.hasnext ()) {String str=it.next (), if (Str.equals ("123")) {int i= List.indexof ("123 "); List.add (i," Lisi ");} SYSTEM.OUT.PRINTLN (list);}}
Concurrency Modification Exception Workaround: Do not use the method of the collection to manipulate elements when iterating.

So what do you want to do with the elements during the iteration?

//Through The Listiterator iterator manipulation element is possible, and the presence of listiterator resolves the error conditions that may occur during the use of iterator iterations.

}

Data structures stored in the list collection

Common structures for data storage are: Stacks, queues, arrays, linked lists

The stack takes a collection of this structure, and the access to the element is characterized by the following:

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 element is 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.

The queue takes a collection of this structure, and the access to the element is characterized by:

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.

The array uses the set of the structure, and the access to the elements is characterized as follows:

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. Such as

The chain list uses 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 data storage structure is the structure of the array , elements and additions slow, Find Fast, so the daily development of query data, traversal data, ArrayList collection is the most commonly used

LinkedList collection data storage structure is a linked list structure, elements and additions and deletions fast, find slow , in the actual development of a set of additions and deletions often involves the end-to-end operation, in the LinkedList set provides a method, as follows

Package Com.oracle.demo2;import Java.util.linkedlist;public class Linkedlistdemo {public static void main (string[] args {Add (); get (); remove ();} /* void AddFirst (e e) Inserts the specified element at the beginning of this list void AddLast (e e) Inserts the specified element at the end of this list */public static void Add () {LINKEDLIST&LT;STRING&G T List = new linkedlist<string> (), List.addlast ("Good study"), List.add ("HelloWorld"); List.addfirst ("Hello"); 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 * when there are no elements in the collection, then the FETCH element will report an exception * Boolea n IsEmpty () If the list contains no elements, returns true */public static void get () {linkedlist<string> list = new linkedlist<string> (); List.addlast ("good study"); List.add ("HelloWorld"); List.addfirst ("Hello"); List.clear (); if (!list.isempty ()) {String s = List.getfirst (); String f = list.getlast (); SYSTEM.OUT.PRINTLN (S + "=========" + f);} Else{system.out.println ("Nosuchelementexception");}} /* * e Removefirst () Remove and return the first element in the list * e removelast () Remove and return the last element in the list * */public static void Remove () {linkedlist< string> list = new linkedlist<string> (), List.addlast ("Good study"), List.add ("HelloWorld"); List.addfirst ("Hello"); System.out.println (List.removefirst ()); System.out.println (List.removelast ()); SYSTEM.OUT.PRINTLN (list);}}

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. Enumeration enumeration has been replaced by Iterators iterator.

Set interface

Features of the set interface: Contrary to the features of the list interface, unordered, repeatable, non-indexed

Package Com.oracle.demo3;import Java.util.hashset;import Java.util.iterator;import Java.util.set;public class Setdemo {public static void main (string[] args) {set<string> Set = new hashset<string> (); Set.add ("123"); Set.add ("ASD"); Set.add ("W34ww"); Set.add ("Dvef"); Set.add ("Dvef");//set without index, unordered//1, iterator traversal iterator<string > it = Set.iterator (); while (It.hasnext ()) {System.out.println (It.next ());} System.out.println ("===============");//2, Enhanced for loop for (String Str:set) {System.out.println (str);}}}

Execution results

HashSet Collection

HashSet implements a set interface, 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 .

Package Com.oracle.demo3;import Java.util.hashset;public class Hashsetdemo {public    static void Main (string[] args) {hash ();}     /* * The data stored in the set is not repeatable     * 1, calculate the hash value of the object you want to store, and then put the hash value in the collection to see    if * There is no same hash value     * 2, holding the hash value in the collection, if there is the same hash value, Then call the Equals method,     *    "AaB". Equals ("AaB"), if identical, returns true to determine that this is a repeating element, throw out     * 3, if the hash value is the same, call the Equals method, and if it returns false, Then deposit set     * *    /public static void hash () {    hashset<string> hs=new hashset<string> ();    Hs.add ("AaB");    Hs.add ("AaB");    Hs.add ("BBC");    Hs.add ("BBC");        SYSTEM.OUT.PRINTLN (HS);    }}

Execution result: [Bbc,aab] indicates that the set collection is not able to store duplicate elements

HashSet storing data for custom types

If you want to ensure that the uniqueness of the data depends on: Hashcode () and Equals () methods

If you give hashset the elements of the type provided in Javaapi, you do not need to override the hashcode and equals methods of the element.

because of these two methods, the JAVAAPI has been rewritten in each class, such as the String class, the integer class, and so on.

Give 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 method to guarantee that the objects in the HashSet collection are unique

Package Com.oracle.demo3;public class Person {String name;int age;    public int hashcode () {    return name.hashcode () +age*55;    }    Public String toString () {    return ' name ' +name+ ' age is ' +age;    }    public boolean equals (Object obj) {    if (obj==null) {    return false;    }    if (this==obj) {    return true;    }    if (obj instanceof person) {    return ((person) obj) .age==this.age&& ((person) obj). name==this.name;    }    return false;    } Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public person (String name, int.) {super (); this.name = Name;this.age = age;} Public person () {}}

Package Com.oracle.demo3;import Java.util.hashset;import Java.util.iterator;public class Test {public static void main ( String[] (args) {//Create HashSet Object hashset<person> HS =new hashset<person> (); Hs.add (New Person ("Zhang San", 18)); Hs.add (New person ("John Doe", "+"), Hs.add ("Harry", "New Person"), Hs.add ("John Doe");iterator<person> it= Hs.iterator (); while (It.hasnext ()) {person p= (person) it.next (); SYSTEM.OUT.PRINTLN (P);}}

  

Linkedhashset Collection

HashSet guarantees that the elements are unique, but the elements are stored in no order, so we need to make sure that the Linkedhashset

in the HashSet there is a subclass Linkedhashset, which is a data storage structure for the combination of linked lists and hash tables.

Package Com.oracle.demo3;import Java.util.linkedhashset;public class Linkedhashsetdemo {public     static void main ( String[] args) {linkedhashset<string> list=new linkedhashset<string> ();        List.add ("123");        List.add ("ASD");        List.add ("3esd");        SYSTEM.OUT.PRINTLN (list);}}

The principle of determining whether a set element is unique

ArrayList the contains method to determine whether the element repeats the principle

The contains method of ArrayList uses the call method when the Equals method of the passed-in element is compared to the old element in the collection, which determines whether there are duplicate elements based on the returned Boolean value. At this point, when ArrayList stores a custom type, it is necessary to override the Equals method of the element, because the custom type determines whether the duplicate is based on the address value before the Equals method is overridden, so if you want to determine whether it is a repeating element based on the content .

HashSet Add/contains and other methods to determine whether the principle of repetition of elements

The set collection cannot hold duplicate elements, and the Add method will determine whether there are duplicate elements when added, which are not added or duplicated.

HashSet The collection is unordered, its judgment is only based on the hashcode of the element type and the return result of the Equals method. The rules are as follows:

the new element and the old element that is already in the collection are first judged Hashcode value

If different, the description is different from the element that is added to the collection.

if the same, then the equals comparison result is judged. Returns true for the same element, or false to add a different element to the collection.

So, using HashSet stores a custom type, if you do not override the class's hashcode with the Equals method, then when you judge the repetition, you use the address value, and if you want to compare elements by content, you need to override the hashcode of the element class with the Equals method.

Java Learning list interface, set interface

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.