9.11. Adding Values To A List — AP CSA Java Review - Obsolete

9.11. 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.

import java.util.*; // import all classes in this package. public class Test { public static void main(String[] args) { List nameList = new ArrayList(); nameList.add("Diego"); System.out.println(nameList); nameList.add("Grace"); System.out.println(nameList); nameList.add("Diego"); System.out.println(nameList); System.out.println(nameList.size()); } }

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.

import java.util.*; // import all classes in this package. public class Test { public static void main(String[] arts) { List list1 = new ArrayList(); list1.add(new Integer(1)); System.out.println(list1); list1.add(new Integer(2)); System.out.println(list1); list1.add(1, new Integer(3)); System.out.println(list1); list1.add(1, new Integer(4)); System.out.println(list1); System.out.println(list1.size()); } }

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.

import java.util.*; // import all classes in this package. public class Test { public static void main(String[] arts) { List list1 = new ArrayList(); list1.add(1); System.out.println(list1); list1.add(2); System.out.println(list1); list1.add(1, 3); System.out.println(list1); list1.add(1, 4); System.out.println(list1); System.out.println(list1.size()); } }

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.

Tag » Add Element If Not In List Java