JAVA common set framework usage explanation basics 2 Colletion subinterface List

Source: Internet
Author: User

JAVA common set framework usage explanation basics 2 Colletion subinterface List

Next, let's talk about the collection of knowledge. In the previous article, we talked about the Collection interface. It can be said to be the ancestor of a set. Let's talk about its children and grandchildren in this article.

1. Collection subinterfaces

List: ordered (the order in which the data is stored and retrieved is the same). The elements are indexed (I .e., the badge), and the elements can be repeated.

Set: the elements cannot be repeated or unordered.

First, let's talk about List.

A. List-specific common methods (all have A common feature that can be used to operate the badge ). The List interface allows you to add, delete, modify, and query elements. The List interface is implemented by subclass:

Now we initialize a List interface:List ll = new ArrayList ();

Next, let's talk about the main common methods of List.

1. Add (add elements by index position)

 

Void add (index, element); void add (index, Collection) // One of the unique retrieve methods of List (inti = 0; I
 
  

 

2. Delete (delete the elements at the corresponding index location)

 

Object remove (index); // returns the deleted element.

 

3. Modify (modify the element at the specified index location and return the element before modification)

 

ObjectSet (index, element) // returns the modified element

 

4. obtain:

 

Object get (index); int IndexOf (object); // returns the index of the specified element for the first time in this list. If this list does not contain this element, returns -1.int lastIndexOf (object); // returns the last time the specified element appears in this list. If this list does not contain this element,-1 is returned. list subList (int from, int to); // contains the header, not the end, and obtains the subList.

 

The test code is as follows:

The Code is as follows: package com. wq. list;/*** Add a course class and provide the course selection * @ author LULEI **/public class Courses {private String id; // The course serial number private String name; // Course name public Courses () {} public Courses (String id, String name) {this. setId (id); this. setName (name);} public String getId () {return id;} public void setId (String id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}}

// Some methods to test the List: package com. wq. list; import java. util. arrayList; import java. util. arrays; import java. util. iterator; import java. util. list; public class ListTest {// used to store the Listpublic List courseToSelect; public ListTest () {this. courseToSelect = new ArrayList ();} // used for courseToSelect to add an alternative course public void testAdd () {// create an instance of a course and use the add method, add this instance // to the optional course List Courses cr1 = new Courses ("1", "Database"); courseToSelect. add (cr1); // add the course to the optional course List Courses temp = (Courses) courseToSelect. get (0); // select the first element System in the List. out. println ("added course:" + temp. getId () + ". "+ temp. getName (); Courses cr2 = new Courses ("2", "JAVA"); courseToSelect. add (0, cr2); Courses temp2 = (Courses) courseToSelect. get (0); System. out. println ("added course:" + temp2.getId () + ". "+ temp2.getName ();/** the following code may encounter an out-Of-The-boundary exception Courses Convention 3 = new Courses (" 4 "," test "); courseToSelect. add (4, 375); // Courses 375 = (Courses) courseToSelect. get (4); // System. out. println ("added course:" + cr3.getId () + ". "+ cr3.getName (); **/Courses cr7 = new Courses (" 1 "," Database "); courseToSelect. add (cr7); // add the course to the optional course List Courses temp7 = (Courses) courseToSelect. get (2); // select the first element System in the List. out. println ("added course:" + temp7.getId () + ". "+ temp7.getName (); // the use of the addAll () method Courses [] 32a = {new Courses (" 3 "," high "), new Courses (" 4 ", "English")}; courseToSelect. addAll (Arrays. asList (); // converts the array to the List set Courses temp3 = (Courses) courseToSelect. get (3); Courses temp4 = (Courses) courseToSelect. get (4); System. out. println ("added two courses:" + temp3.getId () + ". "+ temp3.getName () + temp4.getId () + ". "+ temp4.getName (); Courses [] cr4 = {new Courses (" 5 "," 文 "), new Courses (" 6 "," ")}; courseToSelect. addAll (2, Arrays. asList (cr4); // converts the array to the List set Courses temp5 = (Courses) courseToSelect. get (2); Courses temp6 = (Courses) courseToSelect. get (3); System. out. println ("added two courses:" + temp5.getId () + ". "+ temp5.getName () + temp6.getId () + ". "+ temp6.getName ();}/*** create a Get method to obtain the elements in the List */public void testGet () {int num = courseToSelect. size (); // obtain the length of the List System. out. println ("the following courses can be selected:"); for (int I = 0; I
   
    

 

Note that the previous example uses the foreach statement instead of the Iterator. However, let's look at a code that uses the iterator to traverse the set error:

The main code is as follows:

 

.......... Ll. add ("qwe1"); ll. add ("qwe2"); ll. add ("qwe3"); Iterator it = ll. iterator (); // get the object of the iterator of the List set while (it. hasnext () {Object obj = it. next (); if (obj. equals ("qwe2") {ll. add ("abc9"); // add elements to the set in the iterator} else {System. out. println ("next:" + obj); // print element }}

 

The above is a piece of code, but an exception occurs in running the while loop: Java. util. concurrentModificationException. The main reason is: In the iterator process, do not directly use the set to operate the element, so it is easy to throw an exception. How can this problem be solved ??? We can use the subinterface ListIterator of Iterator to perform more operations on elements in the Iterator.

The change code is as follows:

 

Ll. add ("qwe1"); ll. add ("qwe2"); ll. add ("qwe3"); ListIterator it = ll. listiterator (); // get the object of the iterator of the List set while (it. hasnext () {Object obj = it. next (); if (obj. equals ("qwe2") {it. add ("abc9"); // add an element to the iterator object} else {System. out. println ("next:" + obj); // print element }}

You can use ListIterator to modify the set. You can add or delete the changes in the iterator. The modified results are directly mapped to the set.

 


B. Summary of List subclasses

Vector: contains an array of data structures and is synchronized (I .e. thread-safe ). Query for addition, deletion, and modification is slow. (Not commonly used)

ArrayList: the array data structure is internal and is not synchronized. Instead of Vector, the query speed is fast.

Internal list: the data structure of the two-way linked list is not synchronized. Adding and deleting elements is very fast.

Here we will do an exercise: Use the consumer list to simulate a Data Structure of a stack and a queue.

STACK: First In Last Out FILO

Queue: First In First Out (FIFO)

 

We should describe a container that provides users with a container object to complete these two structures. The queue list (which can implement the queue and stack functions) is commonly used as follows:

--- Add

AddFirst ();

AddLast (); // After jdk1.6, change it to offerFirst (), and offerLast ();

--- Obtain

GetFirst (); // get but not remove, if the linked list is empty. Throw NoSuchElementException

GetLast ();

After JDK 1.6, the above two are changed:

PeekFirst (); // get but not remove. If the linked list is empty, null is returned.

PeekLast ();

--- Delete

RemoveFirst (); // get and remove the current element. If the linked list is empty. Throw NoSuchElementException

RemoveLast ();

After JDK 1.6, the above two are changed:

PoolFirst (); // obtain and remove the current element. If the linked list is empty, null is returned.

PoolLast ();

 

 

The code is implemented as follows:

/// Queue class package com. wq. using list; import java. util. using list; import java. util. list; public class DuiLie {// This class is the queue List ls = new queue List (); // The listpublic DuiLie () {} public void addElement (Object obj) {// ls. addLast (obj); // Add the element ls. offerLast (obj); // After JDK 1.6, add the element method System. out. println (obj + "added to queue");} public void removeElement () {Object obj = ls. pollFirst (); // Delete the first element in jdk1.6, replacing the removeFirst () method System. out. println (obj + "outgoing queue") ;}/// Stack class package com. wq. using list; import java. util. using list; public class DuiZhan {// This class is the function of implementing the stack using list ls = new using List (); // The listpublic DuiZhan () of the chain table structure is used internally () {} public void addElement (Object obj) {// ls. addLast (obj); // Add the element ls. offerLast (obj); // After JDK 1.6, add the element method System. out. println (obj + "added to stack");} public void removeElement () {Object obj = ls. pollLast (); // Delete the first element in jdk1.6, replacing the removeLast () method System. out. println (obj + "has exited the stack") ;}//// test the preceding two classes of package com. wq. using list; public class test {public static void main (String [] args) {// TODO Auto-generated method stubDuiZhan dz = new DuiZhan (); // instantiate the stack object DuiLie dl = new DuiLie (); // instantiate the queue object // implement the stack function System. out. println ("stack implementation"); dz. addElement (111); dz. addElement (222); dz. addElement (333); dz. addElement (444); dz. removeElement (); dz. removeElement (); dz. removeElement (); dz. removeElement (); System. out. println (); // implement the queue function System. out. println ("queue functions"); dl. addElement (111); dl. addElement (222); dl. addElement (333); dl. addElement (444); dl. removeElement (); dl. removeElement (); dl. removeElement (); dl. removeElement ();}}

The running result is as follows:

 

Stack implementation function 111 has been added to stack 222 has been added to stack 333 has been added to stack 444 has been added to stack 444 has exited stack 333 has exited stack 222 has exited stack 111 has exited stack to implement the queue Function 111 has joined the queue 222 has joined the queue 333 has joined the queue 444 has joined the queue 111 has been out of the queue 222 has been out of the queue 333 has been out of the queue 444 has been out of the queue

 

C. ArrayList set storage number custom object

1. Here, I want to mention it. All objects stored in the set are referenced by the object (that is, the absolute address value of the object in the heap), and the iteration in the iterator is also the object reference in the set.

The Code is as follows:

Package com. wq. arraylist; import java. util. arrayList; import java. util. iterator; import java. util. list; import com. wq. person. person;/*** this class removes repeated elements in the ArrayList * @ author LULEI **/public class testArrayList {public static void main (String [] args) {// TODO Auto-generated method stubList li = new ArrayList (); testDemo1 (li);} public static void testDemo1 (List li) {// test the traditional Object/* li. add ("111"); li. add ("111"); li. Add ("222"); li. add ("333"); li. add ("444"); li. add ("333"); * // ** test adding a custom object Person */li. add (new Person ("wq1", 21); li. add (new Person ("wq2", 22); li. add (new Person ("wq1", 21); li. add (new Person ("wq3", 23); li. add (new Person ("wq2", 22); li. add (new Person ("wq3", 23); System. out. println (li); // call the method in exchange for a single element li = getSingelElement (li); System. out. println (li);} public static List getSingelElement (List li) {// TODO Auto-gene Rated method stubList temp = new ArrayList (); // create a Listfor (Iterator it = li. iterator (); it. hasNext ();) {Object obj = it. next (); if (! Temp. contains (obj) {// If the element temp. add (obj) is not included; // add it to the new List} return temp ;}}
First, the next article will introduce the 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.