What is the problem of initiating an ArrayList
by:
new ArrayList<String>().add("something");
And why we should use the following to initiate an ArrayList
:
new ArrayList<String>() {{
add("something");
}};
What is the problem of initiating an ArrayList
by:
new ArrayList<String>().add("something");
And why we should use the following to initiate an ArrayList
:
new ArrayList<String>() {{
add("something");
}};
You should not use double brace initialization! You can but it doesn't mean you should.
To get back to your question
new ArrayList<String>().add("something");
The problem with this is that this actually returns a boolean
: the result of the add
method. The list you just instantiated is lost and will be garbage collected.
What you should do instead is keep a reference to the list and use it to add the value.
List<String> list = new ArrayList<>();
list.add("something");
// or simpler
list = Arrays.asList("something"); // warning fixed-size list
The syntax you are using is wrong. You can get it working if you follow this answer:
Initialization of an ArrayList in one line
ArrayList<String> list = new ArrayList<String>();
list.add("something");
new Array<String>().add("Something");
is not the only way to do this. You could use something like:
Arrays.asList("Something","Something Else");
This returns a List<String>
though.