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:
List<String>
and ArrayList<String>
types are used instead of raw ArrayList
type.list
is declared as List<String>
, i.e. the interface type instead of implementation type ArrayList<String>
.class ArrayList<E> implements List<E>
interface List<E>
E get(int index)
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.
[...] 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.
Variables: Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.