The ArrayList collection is the most common collection in a program, which belongs to the reference data type (Class). A variable-length array is encapsulated inside the ArrayList, and when the deposited element exceeds the lengthof the array,ArrayList allocates a larger array in memory to store the elements. the ArrayList collection can therefore be thought of as a variable-length array.
The creation format of the collection
Guide Package:import java.util.ArrayList;
Create objects: Exactly the same way as other normal reference data types, but specify the data types stored in the container:
arraylist< The data type of the element to be stored > variable name = new arraylist< The data type of the element to store > ();
L The elements stored in the collection can only be specified in <> parentheses in the data type element;
The data type in the < data type > to store element must be a reference data type and cannot be a basic data type;
The following is a representation of the reference data type for the 8 basic data Types :
|
Basic data types |
The corresponding reference data type representation |
|
Byte |
Byte |
|
Short |
Short |
|
I NT |
Integer |
|
Long |
Long |
|
Float |
Float |
|
Double |
Double |
|
Char |
Character |
|
Boolean |
Boolean |
The following is a representation of the reference data type for the 8 basic data Types :
Let's take a few examples to clarify how a collection is created:
L Storing elements of type string
arraylist<string> list = new arraylist<string> ();
L Store data of type int
arraylist<integer> list = new arraylist<integer> ();
L Store phone-type data
arraylist<phone> list = new arraylist<phone> ();
Common methods for collections
function Description
|
method declaration |
|
Boo Lean Add ( object obj " |
will specify the element obj Append to the end of the collection |
|
Object get ( int index ) |
Returns the element at the specified position in the collection |
|
int size () |
Returns the number of elements in the collection |
|
Method declaration |
Function description |
|
Boolean add(int index, Object obj) |
Inserts the specified element, obj , into the specified position in the collection |
|
Object REM o ve(int index) |
Removes the element at the specified index from the collection , returning the element |
|
void Clear() |
Empties all elements in the collection |
|
Object Set(int index, object obj) |
replaces the element at the specified position in the collection with the specified element, obj |
Java ArrayList Collection