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>andArrayList<String>types are used instead of rawArrayListtype. - Variable names starts with lowercase
listis declared asList<String>, i.e. the interface type instead of implementation typeArrayList<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
Answer from polygenelubricants on Stack OverflowVariables: Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.
Videos
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>andArrayList<String>types are used instead of rawArrayListtype. - Variable names starts with lowercase
listis declared asList<String>, i.e. the interface type instead of implementation typeArrayList<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.
}
It would be simpler if you were to just declare it as a fixed-size List (but with mutable elements) - does it have to be an ArrayList?
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
Or if you have only one element:
List<String> places2 = Collections.singletonList("Buenos Aires");
This would mean that places2 is immutable (trying to change it in any way will cause an UnsupportedOperationException exception to be thrown).
To make a variable-size list that is a concrete ArrayList you can create an ArrayList from the fixed-size list:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
And import the correct package:
import java.util.Arrays;
Actually, probably the "best" way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way:
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
The catch is that there is quite a bit of typing required to refer to that list instance.
There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):
ArrayList<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.
What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):
List<String> list = ["A", "B", "C"];
Unfortunately it won't help you here, as it will initialize an immutable List rather than an ArrayList, and furthermore, it's not available yet, if it ever will be.
Use a second ArrayList for the 3 strings, not a primitive array. Ie.
private List<List<String>> addresses = new ArrayList<List<String>>();
Then you can have:
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
addresses.add(singleAddress);
(I think some strange things can happen with type erasure here, but I don't think it should matter here)
If you're dead set on using a primitive array, only a minor change is required to get your example to work. As explained in other answers, the size of the array can not be included in the declaration. So changing:
private ArrayList<String[]> addresses = new ArrayList<String[3]>();
to
private ArrayList<String[]> addresses = new ArrayList<String[]>();
will work.
List<String[]> addresses = new ArrayList<String[]>();
String[] addressesArr = new String[3];
addressesArr[0] = "zero";
addressesArr[1] = "one";
addressesArr[2] = "two";
addresses.add(addressesArr);