ArrayList
The ArrayList
class is part of the java.util
package.
Syntax
ArrayList<DataType> name = new ArrayList<DataType>();
Method Details
ArrayList
public ArrayList()
The ArrayList
constructor allows you to create a new ArrayList
object.
Parameters
Name | Type | Description |
---|---|---|
capacity | int | the specified initial capacity of an |
Examples
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
ArrayList<FoodTruck> myFoodTrucks = new ArrayList<FoodTruck>();
add
public void add(E element)
The add()
method is used to add a specific element to the list.
Parameters
Name | Type | Description |
---|---|---|
element | E | the object to add to the |
Examples
ArrayList<String> test = new ArrayList<>();
// adding elements
test.add("It");
test.add("Is");
test.add("Cold");
// printing all the elements
System.out.println(test);
Output:
[It, Is, Cold]
add
public void add(int index, E element)
The add()
method is used to add an element at a specified index to the list.
Parameters
Name | Type | Description |
---|---|---|
element | E | the object to add to the |
index | int | the position at which to insert the specified element |
Examples
ArrayList<String> test = new ArrayList<>();
// adding elements
test.add("It");
test.add("Cold");
test.add(1, "Is");
// printing all the elements
System.out.println(test);
Output:
[It, Is, Cold]
get
public E get(int index)
The get()
method is used to retrieve the element at a specified position in an ArrayList
.
Parameters
Name | Type | Description |
---|---|---|
index | int | the index of the element to be returned |
Examples
ArrayList<Integer> test = new ArrayList<Integer>(4);
test.add(1);
test.add(2);
test.add(3);
test.add(4);
int element = test.get(2);
System.out.println("The element at index 2 is " + element);
Output:
The element at index 2 is 3
remove
public E remove(int index)
The remove()
method allows you to remove a specific element from an ArrayList
.
Parameters
Name | Type | Description |
---|---|---|
index | int | index of the element to be removed |
Examples
ArrayList<Integer> test = new ArrayList<Integer>(5);
test.add(1);
test.add(2);
test.add(3);
test.add(4);
System.out.println("Size of list: " + test.size());
test.remove(2);
System.out.println("Size of list: " + test.size());
Output:
4
3
size
public int size()
The size()
method returns the number of elements in an ArrayList
.
Examples
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(10);
myNumbers.add(20);
myNumbers.add(30);
int totalNumbers = myNumbers.size();
System.out.println("Size of list is " + totalNumbers);
Output:
Size of list is 3
set
public E set(int index, E element)
Replaces the element at the specified position in the list with the specified element and returns the element previously at the specified position.
Parameters
Name | Type | Description |
---|---|---|
index | int | the index of the element to replace |
element | E | the element to be stored at the specified position |