I genius official free Tutorial 31: List collection of the Java Collection framework

Source: Internet
Author: User
Tags object object

Collection Frame

As you can see in the use of arrays, it is cumbersome to insert and delete elements into an array, and the length of the array cannot be changed. Java provides us with a container that is more convenient to store data in bulk, that is, a collection.
Collections and arrays are all intended to use a variable to store a batch of data, but the collection is easier to use and the length of the collection can vary.

List Interface

The list collection can store ordered, repeatable data;
Common subclasses are ArrayList and LinkedList two classes

ArrayList class

This is a collection class that is implemented by an array, and is encapsulated in arrays.

Example: Package collection.list.arraylist;import java.util.arraylist;/** * arraylistdemo class   *  demonstrates the use of common methods in ArrayList classes  *  @author   Genius Federation  -  Yukun  */public class  Arraylistdemo {public static void main (String[] args)  {//When you create a ArrayList object, The bottom layer creates an empty array of type Object Arraylist arraylist = new arraylist ();//loops into the data for  (int  element = 1; element <= 11; element++)  {/* *  Adding data to the collection through the Add method of the ArrayList  *  any type of data is converted to the object type to join the collection  *  when the data for the collection is the data of the base data type  *  The data from the base data type is converted to the corresponding wrapper class type  *  For example: data of type int is converted to an integer type  *  and then the integer type is converted to the object type  *   The process of converting from a basic data type to a wrapper class type is called auto-boxing  *  This conversion process is done automatically by the system  *  *  when the first data is added. The bottom layer re-creates an array of type object of length 10  *  here The 101 thinks is the initial length of the ArrayList collection  *  and stores the first data in a position labeled 0 under the underlying object type array;   *  when the underlying array is full, and then adds elements to the collection, the,  *  creates a length of the original array1.5 times times the new array  *  here 1.5 is called the growth factor of the collection  *  and copies all the elements in the original array into the new array  *  then adds the current element to the position where the new array is labeled as the original array length   *  *  For example: For the first time in this example, when the 11th element is deposited, that is element==11  *  the length of the original array is 10 (the maximum subscript is 9)  *  The bottom layer creates a new array of type object with a length of 15 (10 1.5 times times)  *  then copies all the data from the original array into the new array  *  then deposits the element in the position labeled 10 in the new array 11  *   Note: The element here is not the index of the set, but the elements (data) that are stored in the collection (the maximum value of the maximum number of storage elements is int type 2147483647 [0x7fffffff] */ Arraylist.add (element);} /* *  loop out the data  *  here the index represents the set of subscripts  *  the length of the collection is obtained using the size method, not the length property, nor the length method  *   Gets the length of the array used by the Lengths property  *  gets the length of the string using the Len method  */for  (int index = 0;  index < arraylist.size ();  index++)  {//  Use the Get method to get the data in the collection, The obtained data type is Objectobject element = arraylist.get (index);//  coercion type conversion integer data =   (Integer) Element;/* * integer is a reference type  *  so the question is, why can the variable e of the base data type be assigned a value of the reference type?  *  because integer is the wrapper class for int  *  from the packageThe process of converting an assembly type to a basic data type, called an automatic unpacking  *  This conversion process is also done automatically by the system  */int e = data;// Each loop outputs the value of the variable e and two spaces System.out.print (e +  "  ");}} Running Result: 1  2  3  4  5  6  7  8  9   10  11
Summary:

1, the initial length of the set is 10, the growth factor is 1.5
2, the theoretical maximum storage length is the maximum value of type int 2147483647 [0X7FFFFFFF]
3. Automatic boxing when depositing data of basic data type
4. When generics are not used, the data type of the data being fetched is object
5. Get the set length using the Size method
6, through the results can be seen, the order of extraction and the order of deposit is consistent, so it is an orderly set
7, the bottom layer is implemented by the array, its memory space is continuous, so query elements faster
8, insertions and deletions are slow because the elements after the insertion position are moved back, and the elements after the delete position are moved forward in turn

Example: demonstrating the use of common methods in the ArrayList class package collection.list.arraylist;import java.util.arraylist;import  Java.util.arrays;/** * arraylistdemo Class  *  Demo use of common methods in ArrayList classes  *  @author   Genius Federation  -  Yukun  */public class arraylistdemo2 {public static void main ( String[] args)  {//Create ArrayList object Arraylist arraylist1 = new arraylist (); Arraylist arraylist2 = new arraylist ();//Cyclic data for  (int element = 1;  element <= 3; element++)  {//three elements Arraylist1.add (element) in both sets after the end of the cycle. Arraylist2.add (element);} Traversing a set; running result: 1  2  3ergodicarraylist (arrayList1);/* *  inserting data, inserting data into the position labeled 1 in the collection 10  *  the subscript value that you insert must be less than or equal to the collection length  *  that is, insert the subscript <= collection. Size (); *  If the insertion subscript is larger than the set length, Indexoutofboundsexception */arraylist1.add (1,10) will appear;//Iterate through the collection of inserted data; run result:1  10  2   3ergodicarraylist (ARRAYLIST1);Add each element of the ArrayList2 collection to the collection ArrayList1 in turn arraylist1.addall (ARRAYLIST2);//traverse the collection after inserting the data; run result:1  10   2  3  1  2  3ergodicarraylist (ArrayList1);//contains method, Determines whether the collection contains an element boolean iscontains = arraylist1.contains (10);// Output result: Whether the collection ArrayList1 contains 10:truesystem.out.println ("collection ArrayList1 contains:"  + iscontains); Output result: Whether the collection ArrayList1 contains 11:falsesystem.out.println ("collection ArrayList1 contains one:"  + arraylist1.contains (11));// The IndexOf method, which gets the subscript for the first occurrence of an element in the left-hand side of the collection/output: The subscript for the first occurrence of 2 in the collection ArrayList1 is: 2system.out.println (the subscript for the first occurrence of 2 in the collection ArrayList1 is: "  + arraylist1.indexof (2));//lastindexof method, gets the subscript//of the last occurrence of an element in the collection (right first time) Output: The last occurrence of 2 in the collection ArrayList1 is: 5system.out.println ("The subscript for the last occurrence of 2 in the collection ArrayList1 is:"  +  Arraylist1.lastindexof (2));//remove method, remove the element corresponding to the subscript//If the input argument type is byte, short, int, and char type, remove the Arraylist1.remove (0) according to the subscript; /Running Result: 10  2  3  1  2  3  ergodicarraylist ( ARRAYLIST1)//Remove ArraYList1 element 3 in the collection will only remove data on the first match on the Left Arraylist1.remove ((Integer) 3);//Run Result: 10  2  1  2   3 ergodicarraylist (ArrayList1);//set method, update the corresponding subscript element arraylist1.set (3,1000);//Run Result: 10  2   1  1000  3 ergodicarraylist (ArrayList1);//toarray method, Converts a collection to an array of type Object Object[] array = arraylist1.toarray ();//Converts an array to a string form string str =  arrays.tostring (array);//Run Result: [10, 2, 1, 1000, 3]system.out.println (str);// Empties all the elements in the collection arraylist1.clear ();//isempty method, determines whether the collection is empty, and returns true//if and only if the size method obtains a result of 0 o'clock Run Result: Whether the collection arrayList1 is empty: TrueSystem.out.println ("The collection ArrayList1 is empty:"  + arraylist1.isempty ());} /** *  Traversal Collection  */private static void ergodicarraylist (ArrayList arrayList) {// Loop out Element for  (Int index = 0; index < arraylist.size ();  index++)  {   using the Get method to get the data in the collection, the data type obtained is Objectobject element = arraylist.get (index);* *  when you use the System.out.println () method to output an object of a reference type directly  *  output is an object. The return value of the ToString () method  *  for example:  * &NBSP;SYSTEM.OUT.PRINTLN (Element); and  * system.out.println (Element.tostring ()); it's the same  */. System.out.print (element);//Output two spaces System.out.print ("  ");} NewLine System.out.print ("\ n");}} Run result:1  2  3  1  10  2  3  1   10  2  3  1  2  3   Whether the collection ArrayList1 contains the 10:true collection ArrayList1 contains the 11:false collection arrayList1 the subscript for the first occurrence of 2 is: 2 The last occurrence of 2 in the set ArrayList1  2  3  1  2  3  10  2  1  &NBSP;2&NBSP;&NBSP;3&NBSP;&NBSP;10&NBSP;&NBSP;2&NBSP;&NBSP;1&NBSP;&NBSP;1000&NBSP;&NBSP;3&NBSP;&NBSP;[10, &NBSP;2,&NBSP;1,&NBSP;1000,&NBSP;3] Collection ArrayList1 is empty: true


Another vector collection class, and the difference between the ArrayList: ArrayList is thread asynchronous (thread insecure), vector is thread synchronization (thread-safe), so the performance of vector collection is very low, has been basically not used, interested students can understand

Since ArrayList collection insertions and deletions are inefficient, are there any faster than that?
Next look at the LinkedList collection class

LinkedList class

And the ArrayList class basically the same, ArrayList some methods LinkedList have, but they are implemented in different ways, linkedlist with a doubly linked list of data structure implementation, when adding elements to the collection, the collection will create a node, This node stores the currently added elements and stores the previous node and the next node, thus forming the data structure of the doubly linked list.
The efficiency of the structure modification and deletion is very efficient, but the nodes and nodes in this structure are not contiguous in the memory space, so the query efficiency is lower than that of the ArrayList set.

Example: Demo LinkedList partial specific method package collection.list.linkedlist;import java.util.linkedlist;/** *  Linkedlistdemo Class  *  Demo use of common methods in Linkedlistdemo classes  *  @author   Genius Federation  -  Yukun  */ Public class linkedlistdemo {public static void main (String[] args)  {/ /Create LinkedList Object Linkedlist linkedlist = new linkedlist ();for  (int i = 0 ;  i < 4; i++)  {//Loop adds data Linkedlist.add (i+1) to the collection;} Running Result: 1  2  3  4  ergodiclinkedlist (LinkedList);//Gets the element in the first position in the collection object  first = linkedlist.getfirst ();//Run Result: The first element in the collection is: 1system.out.println ("The first element in the collection is:"  +  first);//Gets the element of the last position in the collection object last = linkedlist.getlast ();//Run Result: The last element in the collection is: 4system.out.println (The last element in the collection is:  + last);//Insert Element Linkedlist.addfirst (0) at the first position of the collection,//Insert element Linkedlist.addlast (6) at the last position of the collection; /Running Result: 0  1  2  3&nbsP; 4  6  ergodiclinkedlist (LinkedList);//Remove the element Linkedlist.removefirst () from the first position in the collection;// Removes the element linkedlist.removelast () from the last position in the collection;//Run result:1  2  3  4   Ergodiclinkedlist (LinkedList);} /** *  Traversal Collection  */private static void ergodiclinkedlist (LinkedList linkedList) {/ /Loop out Element for  (Int index = 0; index < linkedlist.size ();  index++)  {//  use the Get method to get the data in the collection, the data type obtained is Objectobject element = linkedlist.get (index);/* *   When you use the System.out.println () method to output an object of a reference type directly  *  the output is an object. The return value of the ToString () method  *  for example: *  SYSTEM.OUT.PRINTLN (Element); and  * system.out.println (Element.tostring ()); it is the same  */system.out.print ( Element);//Output two spaces System.out.print ("  ");} NewLine System.out.print ("\ n");}} Run result:1  2  3  4   The first element in the collection is: 1 the last element in the set is: 40  1  2   3  4 &nbsP;6  1  2  3  4 



Read more: "I genius official free Tutorial 36: Bi-directional list structure of Java data structure"

Summarize:

The two collections we mentioned above are inherited from the list interface, they have common characteristics, the values are stored sequentially, can be stored in duplicate values, you can use the subscript to access the element
Different points
ArrayList: The bottom layer is implemented by an array with an initial length of 10 and a growth factor of 1.5
Cons: Less efficient insertion and deletion
Advantages: High efficiency in modification and query
LinkedList: The bottom layer is implemented by a doubly linked list with no initial length and growth factor
Advantages: High efficiency in insertion and removal
Cons: Less efficient query and modification

This article from the "Genius Union Education Official Blog" blog, reproduced please contact the author!

I genius official free Tutorial 31: List collection of the Java Collection framework

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.