Getting and Setting Values in a List

You can get the object at an index using obj = listName.get(index) and set the object at an index using listName.set(index,obj).

Note

Remember that you can get the value at an array index using value = arrayName[index]. This is different from how you get the value from a list using obj = listName.get(index). You can set the value at an index in an array using arrayName[index] = value, but with lists you use listName.set(index, object).

Removing an Object at an Index

You can also remove an object at an index in a list using remove(index) which returns the removed object and shifts the remaining objects past the index left one index.

Note

The remove(int index) method will remove the object at the index and shift left any values to the right of the current index. It doesn’t remove the object that matches the integer value given. In the example above it doesn’t remove the 1. It removes the 2 at index 1.

Check your understanding

You can step through the code above by clicking on the following Example-8-6-1.

You can step through the code above by clicking on the following Example-8-6-2.

You can step through the code above by clicking on the following Example-8-6-3.

You can step through the code above by clicking on the following Example-8-6-4.

You can step through the code above by clicking on the following Example-8-6-5.

Next Section - Looping Through a List