TheNewBoston – Intro to Arrays
(arrays are not the same as ArrayLists, but it might be useful to look at this simpler version of arrays)
(More advanced) 10 Examples using ArrayLists
Creating an empty ArrayList that contains String objects:
ArrayList<String> names = new ArrayList<String>();
An ArrayList can hold any type of object – the class name of the object goes inside the <angle brackets>. All items in the ArrayList must be of that type.
This won’t actually work until you import ArrayList at the top of your program:
import java.util.ArrayList;
The <String> part shows that this ArrayList will hold String objects. It can also hold any other type of objects, including objects from a class that you defined yourself.
Adding an item to an ArrayList:
names.add("Jane");
This uses the add() method of an ArrayList object. The type of object must match the ArrayList’s data type.
Getting items from an ArrayList:
names.get(0); names.get(1);
Example that creates ArrayList, adds an item, and gets the item to print it:
import java.util.ArrayList; public class ALexample { public static void main(String[] args) { ArrayList<String> myList = new ArrayList<>(); myList.add("example string"); System.out.println(myList.get(0)); } }
Printing every item from an ArrayList using a for loop:
for (int i = 0; i < names.size() ; i++) { System.out.println(names.get(i)); }
Here we use get(i) to get one of the Strings, and the value of i keeps changing as the loop repeats.
names.size() is the number of Strings in the ArrayList<String>. Notice how the loop uses names.size() as its stop condition above.
Using an “enhanced” or “for each” loop to print every String in an ArrayList<String>:
for (String n: names){ System.out.println(n); }
This is a less verbose way to iterate through an ArrayList. Notice that we didn’t have to use the size() method – it automatically loops the correct number of times.
This for each loop uses the variable n to represent each name, one at a time, and it changes each time the loop repeats. Unlike the regular for loop, the variable is the String (or other object) itself instead of an integer counter variable.