We can get the size of an ArrayList using the .size() method:
List<Integer> ourArray = new ArrayList<>(List.of(50, 40, 30));
// Printing the size:
System.out.println(ourArray.size()); // Output: 3
// Changing the ArrayList:
ourArray.remove(2);
// Printing the new size:
System.out.println(ourArray.size()); // Output: 2
Using the size
We can use the size to access items from the end of an ArrayList.
Because ArrayLists are 0-indexed, the index of the last item is size - 1:
List<Integer> ourArray = new ArrayList<>(List.of(50, 40, 30));
int size = ourArray.size();
// Printing the last item:
System.out.println(ourArray.get(size - 1)); // Output: 30
// Printing the second to last item:
System.out.println(ourArray.get(size - 2)); // Output: 40
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
