Why no default values in ArrayList ??
java - Initialization of an ArrayList in one line - Stack Overflow
Initializing an empty ArrayList (Java)
How do I declare an ArrayList in a default constructor?
Videos
If I am not wrong, objects are created inside the heap memory so they have a default value, in the case of array it is 0 but why is there no default values in ArrayList why is the output empty for an ArrayList ?? since it is also created inside heap memory. then why this difference ?? since ArrayList has default/initial size 10 I was expecting 10 zeros or 10 null values, or something like that would have made more sense. But instead what we get is an empty ArrayList [ ] . why ??
int arr[]=new int[5];
for(int i=0;i<=arr.length-1;i++){
System.out.print(arr[i]+" ");
//output is 0 0 0 0 0
}
ArrayList num=new ArrayList();
System.out.println(num);
//output [ ]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.