I come from C++, and wonder if Java has something like initialize_list
in C++11 which can be used to initialize almost all containers.
I've done some search:
- some approaches looks good such as
List.of()
ofArrays.asList()
, but they createimmutable
collections, and if you want mutable one, you have to do something like
List<Integer> list = new ArrayList<>(List.of(1,2,3))
which will incur copy cost.(Not sure if compiler can optimize this out, but I guess no)
- If I want to do this efficiently, maybe I can only do it in the most plain way?
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Stream
looks ok, but a little bit verbose, and I'm not sure about its efficiency...
So is there any approach that are both elegant and efficient to do this? Maybe it's not appropriate to compare Java and C++ in this way....but I'm just curious.