Very simple question, I think. How do I initialise an ArrayList
called time
.
Thanks.
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.
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.
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.
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.
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");
}};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With