Adding Values to a ListΒΆ

You can add values to a list. If you use add(obj) it will add the passed object to the end of the list. Run the code below to see how the list changes as each object is added.

Note

Notice that we added the same string to the list more than once. Lists can hold duplicate objects.

There are actually two different add methods in the List interface. The add(obj) method adds the passed object to the end of the list. The add(index,obj) method adds the passed object at the passed index, but first moves over any existing values to higher indicies to make room for the new object.

Note

Lists can only hold objects, not primitive values. This means that int values must be wrapped into Integer objects to be stored in a list. You can do this using new Integer(value) as shown above. You can also just put an int value in a list and it will be changed into an Integer object automatically. This is called autoboxing. When you pull an int value out of a list of Integers that is called unboxing.

The code below has the same result as the code above. The compiler will automatically wrap the int values in Integer objects.

Check your understanding

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

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

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

Next Section - Getting and Setting Values in a List