ArrayList is the list class of Java, in the project development is very common, then how to add, delete, modify, query, traverse ArrayList? This article will be elaborated in detail.
Tools/Materials
First, the method of adding ArrayList
- 1
Method 1: Add data to the ArrayList sequentially in sequence.
Usage:
Add A to List
List.add ("a");
#例子:
- 2
Method 2: Add a second data after the nth data
Usage:
Add an E after the 1th element
List.add (1, "E");
Note: There must be enough data in the ArrayList, such as there is no data in the ArrayList, this time using Arraylist.add (1, "E"), there will be a java.lang.IndexOutOfBoundsException exception.
#例子:
- 3
Method 3: Add all the data from one ArrayList to another arralist
Usage:
Add all data from List2 to List1
List1.addall (LIST2);
#例子:
- 4
Method 4: Add all the data from one ArrayList to the nth element in the other arralist.
Usage:
Adds all the data from List2 to the 2nd element in List1.
List1.addall (2,LIST2);
#例子:
END
Second, the deletion method of ArrayList
- 1
Method 1: Delete individual data by location
Usage:
Delete the 2nd data in the list
List.remove (2);
Note: the position is calculated starting from 0 (0, 1, 2, 3 ...)
#例子
- 2
Method 2: Delete individual data by content
Usage:
Remove the data "D" from the list
List.remove ("D");
Note: raw type data such as Int,string,char can be deleted, but for complex objects, such as the user class and the person class object that you write, you need to override the Equals method, which is responsible for removing the Remove method.
#例子
- 3
Method 3: Delete multiple data at the same time as the collection
Usage:
Follow the data in List2 to remove List1
List.removeall (LIST2);
#例子
- 4
Method 4: Empty the ArrayList
Usage:
Clear List
List.clear ();
#例子
END
Three, the modification method of ArrayList
- 1
Method 1: Modify the element at the specified location
Usage:
Change the 2nd element in the list to M
List.set (2, "M");
Note: the position is calculated starting from 0 (0, 1, 2, 3 ...)
#例子
END
Iv. Query of ArrayList
Method 1: get the specified position element
Usage:
Gets the 2nd element in the list
String ele = List.get (2);
Note: the position is calculated starting from 0 (0, 1, 2, 3 ...)
#例子
How to use Java ArrayList