ArrayList
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(99);
numbers.add(22);
numbers.add(8);
System.out.println(numbers);
numbers.set(2, 88);
System.out.println(numbers);
numbers.remove(0);
System.out.println(numbers);
for (int i=0; i<numbers.size(); i++) {
if(numbers.get(i).equals(22)) {
System.out.println("22 at position: " + i);
}
}
System.out.println("88 at position: " + numbers.indexOf(88));
System.out.println("99 at position: " + numbers.indexOf(99));
}
}
The snippet result is
[99, 22, 8]
[99, 22, 88]
[22, 88]
22 at position: 0
88 at position: 1
99 at position: -1
You can use the add method to add an item to the ArrayList. You can use the set method to modify an item in the ArrayList. You can use the remove method to delete an item from the ArrayList. You can use the indexOf to find an item. If you cannot find the item, the index will return -1. You can also use the equals method to find the item.
Data Type
You can use String directly as an ArrayList data type. You can use the primitive type's wrapper class type as the ArrayList data type, including Integer for int type, Character for char type, and Double for double type.
You can also declare a class type as an ArrayList data type. For example, you declare a User class, has name and phoneNumber fields. and as a ArrayList datatype.
ArrayList<User> users
users.get(0).getName(0) means Jenny
users.get(0).getPhoneNumber(0) means 310-775-5150
0
Jenny
310-775-5150
1
Jams
952-516-8073
2
Kevin
917-670-1686
Last updated