How to use an array list in Java?

The following snippet gives an example that shows how to get an element from a List at a specified index, and also how to use the advanced for-each loop to iterate through all elements:

    import java.util.*;

    //...

    List<String> list = new ArrayList<String>();
    list.add("Hello!");
    list.add("How are you?");

    System.out.println(list.get(0)); // prints "Hello!"

    for (String s : list) {
        System.out.println(s);
    } // prints "Hello!", "How are you?"

Note the following:

  • Generic List<String> and ArrayList<String> types are used instead of raw ArrayList type.
  • Variable names starts with lowercase
  • list is declared as List<String>, i.e. the interface type instead of implementation type ArrayList<String>.

References

API:

  • Java Collections Framework tutorial
  • class ArrayList<E> implements List<E>
  • interface List<E>
    • E get(int index)
      • Returns the element at the specified position in this list.

Don't use raw types

  • JLS 4.8 Raw Types

    The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

  • Effective Java 2nd Edition: Item 23: Don't use raw types in new code

    If you use raw types, you lose all the safety and expressiveness benefits of generics.

Prefer interfaces to implementation classes in type declarations

  • Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces

    [...] you should favor the use of interfaces rather than classes to refer to objects. If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types.

Naming conventions

Variables: Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.


A List is an ordered Collection of elements. You can add them with the add method, and retrieve them with the get(int index) method. You can also iterate over a List, remove elements, etc. Here are some basic examples of using a List:

List<String> names = new ArrayList<String>(3); // 3 because we expect the list 
    // to have 3 entries.  If we didn't know how many entries we expected, we
    // could leave this empty or use a LinkedList instead
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.get(2)); // prints "Charlie"
System.out.println(names); // prints the whole list
for (String name: names) {
    System.out.println(name);  // prints the names in turn.
}