Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising An ArrayList [duplicate]

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

Thanks.

like image 431
sark9012 Avatar asked Nov 18 '10 09:11

sark9012


People also ask

How do you initialize an ArrayList of doubles in Java?

public ArrayList<Double> doubleList = new ArrayList<>(); From Java 1.7 , you don't need to write Double while initializing ArrayList , so it's your choice to write Double in new ArrayList<>(); or new ArrayList<Double>(); or not.. otherwise it's not compulsory.

How do you duplicate an ArrayList?

The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object.

Is duplicate allowed in ArrayList?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

Can you initialize an ArrayList?

To initialize an ArrayList in Java, you can create a new ArrayList with new keyword and ArrayList constructor. You may optionally pass a collection of elements, to ArrayList constructor, to add the elements to this ArrayList. Or you may use add() method to add elements to the ArrayList.


1 Answers

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");
}};
like image 158
aioobe Avatar answered Sep 29 '22 00:09

aioobe