April 16, 2018 Java

Source: Internet
Author: User
Tags addall

Java ArrayList Summary

ArrayList is also the most important implementation class in our collection, and it is also a collection class that we have to master. This article will do a more comprehensive summary of ArrayList,

One is conceptually understood, the second is the use of ArrayList, where the use of ArrayList is basically a combination of generics to explain the use, because the actual use is also combined with generics.

A ArrayList

ArrayList is a dynamic array, a subclass of array, and an implementation class for the list interface. Has the characteristic of the array, also has its own characteristic.

(a) ArrayList can dynamically change the size, dynamic increase, delete elements

(ii) Implementation of the collection and list interface, which can be used in the method

Two Commonly used methods of ArrayList

(i) public intsize ();

Returns the number of elements in this list.

(ii) Public boolean isEmpty ();

Returns true if there are no elements in this list

(iii) Public boolean contains (Object O);

Returns true if the specified element is contained in this list

(iv) public int indexOf (Object o)

Returns the index of the specified element that first appeared in this list, or 1 if the list does not contain elements.

(v) public int lastIndexOf (Object o)

Returns the index of the specified element that occurred last in this list, or 1 if the list does not contain an index.

(vi) Public object[] ToArray ();

Returns an array containing all the elements in this list, in the appropriate order (from the first to the last element).

(vii) Public E get (int index);

Returns the element at the specified position in this list

(eight) public E set (int index, e element);

Replaces the element at the specified position in this list with the specified element. The return value is the element that was previously at that specified position

(ix) The public boolean add (E element);

Adds the specified element to the tail of this list. Add successful return True

(10) public void Add (int index, E Element)

Inserts the specified element into the specified position in this list. Moves the element that is currently at that position (if any) and all subsequent elements (indexed by 1) to the right.

(11) Public E Remove (int index)

Removes the element from the specified position in this list, returning the element removed from the list

(12) Public boolean remove (Object o)

Removes the specified element (if any) that first appears in this list. If the list does not contain this element, the list does not change.

(13) public void Clear ()

Removes all the elements from this list. When this call returns, the list will be empty

(14) Public boolean addall (Collection c)

Adds all elements in the collection to the end of this list, according to the order of elements returned by the iterator that specifies collection

(15) Publicboolean addall (int index, Collection c)

Inserts all elements from the specified collection into this list, starting at the specified location.

Three ArrayList additions and deletions to search

  Packagecom.xykj.arraylist; Importjava.util.ArrayList; ImportJava.util.Iterator;  Public classMainClass {/*** ArrayList and additions and changes to the operation **/       Public Static voidMain (string[] args) {//instantiate ArrayList, generics are basic type string, add data can only be string, no errorarraylistlist=NewArraylist<>(); //Add ActionList.add ("123"); //List.add (n);//will errorList.add ("Xiao Ming"); List.add ("Meizi"); List.add ("Shuaige"); //Delete OperationList.remove (1);//Delete the second data as a cursor "xiaoming"List.remove ("Meizi");//Delete the third data "Meizi" with the contents of the actual collection//Data ModificationList.set (0, "222");//Change the contents of the first element to "222".//displaying data within a collection//The two-page elements of "222" and "Shuaige" are left in the collection.//Display Method 1://System.out.println (list);//The simplest way to display//Display Method 2:       /*for (int i = 0; I iterator=list.iterator ();         while (Iterator.hasnext ()) {System.out.println (Iterator.next ()); }      }     }  

Show Results:

The basic operation of adding and modifying the ArrayList is done, and the method of addition and modification is basically fixed, but the method of deleting and finding is more, this example lists all the display list methods.

The second method is often used in Java basics,

The third method is a special for structure called a foreach statement, which does not have an explicit cursor value, but can traverse all the elements of the subsequent collection (array).

The fourth method is a method specifically used by the Java collection that requires the use of an iterator iterator interface, followed by generics (the data type to be received), using the Hasnext method to determine if there is an element in the next cursor position, and then using the next method to get the elements of the collection.

It is worth saying that when deleting many collection elements, it is basic to use the Remove method of the iterator iterator interface to remove the element, and other methods may cause the program to crash.

The use of custom data types as generics, but also the deletion and modification of the operation implementation, but the focus is the delete operation.

1. First build a custom data class user

  1.  PackageCom.xykj.arraylist2;  Public classUser {//define three basic properties for a userString name= ""; String Sex=""; intAge=0; //using construction methods to pass parameters     PublicUser (Stringname, stringsex,intage) {Super();  This. Name =name;  This. Sex =sex;  This. Age =Age ; }           //get and set methods for each parameter     PublicString GetName () {returnname; }       Public voidsetName (String name) { This. Name =name; }       PublicString Getsex () {returnsex; }       Public voidsetsex (String sex) { This. Sex =sex; }       Public intGetage () {returnage; }       Public voidSetage (intage) { This. Age =Age ; }              }     

2. Re-building the Main method invocation class

  1. importjava.util.ArrayList;  Importjava.util.Iterator; Publicclass MainClass {/*** This example makes additions and deletions to generic types that are custom classes * **/       Public Static voidMain (string[] args) {//This is not the basic data type, but the object of the user class created above .ArrayList list = newarraylist<>(); //add an object of user class 10        for(inti = 0; I < 10; i++) {List.add (NewUser ("name" +i, "female", 10 +i)); }         //Delete the previous five user objects       /*use the For loop to delete *for (int i = 0; i < 5; i++) {//Although the program did not collapse, but the results were not *list.remove (i);} Get results: Left name1, Name3, Name5, Name7, Name9*/         //Delete using iterators iteratorIterator Iterator =List.iterator (); intnum = 0;  while(Iterator.hasnext ()) {iterator.next ();//the cursor points to the next, this is important, no errorIterator.remove (); Num++; if(num = = 5) {//Delete Front 0 to 4, exit loop now               Break; }         }         //Create a User objectUser meizi=NewUser ("Meizi", "female", 18); //change the value of the first element in a collectionList.set (0, Meizi); //displays the specific properties of the elements inside the collection//System.out.println (list);//Direct printing appears to be the class name and address, not the result we want        for(User user:list) {System.out.println (User.getname ()+ "\ T" +user.getsex () + "\ T" +user.getage ()); }      }  }

Operation Result:

This example is primarily a generic extension, which is also commonly used in later data storage.

Another is the list of methods to delete multiple elements, Iterators iterator interface class use, this is also the key to grasp the knowledge.

From the above two examples, you can see ArrayList in the actual application of the specific code, to master the two storage methods. The reserves of the relevant knowledge are also needed.

April 16, 2018 Java

Related Article

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.