9

Very simple question, I think. How do I initialise an ArrayList called time.

Thanks.

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
sark9012
  • 5,485
  • 18
  • 61
  • 99

5 Answers5

15

This depends on what you mean by initialize. To simply initialize the variable time with the value of a reference to a new ArrayList, you do

ArrayList<String> time = new ArrayList<String>();

(replace String with the type of the objects you want to store in the list.)

If you want to put stuff in the list, you could do

ArrayList<String> time = new ArrayList<String>();
time.add("hello");
time.add("there");
time.add("world");

You could also do

ArrayList<String> time = new ArrayList<String>(
    Arrays.asList("hello", "there", "world"));

or by using an instance initializer

ArrayList<String> time = new ArrayList<String>() {{
    add("hello");
    add("there");
    add("world");
}};
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • `ArrayList time = new ArrayList();` ? Why not `List time = new ArrayList();` ? (Variables should point to interfaces whenever possible) – Sean Patrick Floyd Nov 18 '10 at 10:09
  • 2
    But how should I tell if this is possible in the OP's scenario? (Perhaps he has `time.ensureCapacity(1000)` right below.) Why complicate things for such a beginner question? – aioobe Nov 18 '10 at 10:13
6

Arrays.asList allows you to build a List from a list of values.

You can then build your ArrayList by passing it the read-only list generated by Arrays.asList.

ArrayList time = new ArrayList(Arrays.asList("a", "b", "c"));

But if all you need is a List declared inline, just go with Arrays.asList alone.

List time = Arrays.asList("a", "b", "c");
Vincent Robert
  • 35,564
  • 14
  • 82
  • 119
1

< 1.5 jdk

List time = new ArrayList();

gt or eq 1.5 jdk

List<T> time = new ArrayList<T>();
jmj
  • 237,923
  • 42
  • 401
  • 438
1
ArrayList<String> time = ArrayList.class.newInstance();
asela38
  • 4,546
  • 6
  • 25
  • 31
  • 2
    Don't write code like this. Don't recommend other people write code like this. It is significantly slower than `new` ... and you have to deal with 2 checked exceptions. (And since your code doesn't deal with the exceptions, it is technically wrong as well.) – Stephen C Nov 18 '10 at 09:58
0

Alternative:

Using Google Collections, you could write:

import com.google.collect.Lists.*;

List<String> time = newArrayList();

You could even specify the initial contents of List as follows:

List<String> time = newArrayList("a", "b", "c");
missingfaktor
  • 90,905
  • 62
  • 285
  • 365