Initialising An ArrayList

35,634

Solution 1

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");
}};

Solution 2

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");

Solution 3

< 1.5 jdk

List time = new ArrayList();

gt or eq 1.5 jdk

List<T> time = new ArrayList<T>();

Solution 4

ArrayList<String> time = ArrayList.class.newInstance();
Share:
35,634
sark9012
Author by

sark9012

Updated on July 11, 2022

Comments

  • sark9012
    sark9012 almost 2 years

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

    Thanks.

  • sark9012
    sark9012 over 13 years
    Before the constructor, I define attributes like private int day; private double hours;
  • Stephen C
    Stephen C over 13 years
    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.)
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    ArrayList<String> time = new ArrayList<String>(); ? Why not List<String> time = new ArrayList<String>(); ? (Variables should point to interfaces whenever possible)
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    This is java 1.4 code. Please use List<String> time = new ArrayList<String>(); instead
  • aioobe
    aioobe over 13 years
    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?