1

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:

  1. some approaches looks good such as List.of() of Arrays.asList(), but they create immutable 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)

  1. 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);
  1. 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.

Ziqi Liu
  • 2,931
  • 5
  • 31
  • 64
  • 3
    Unfortunately, array initializers are only supported by arrays. You can wrap that array in a list, but then the list will be of fixed size, like `Arrays.asList` (which you can actually alter the contents of; you just can't alter the length). If you want a list whose size can change, you will incur a copy operation to get something like an `ArrayList`. – khelwood Nov 15 '19 at 08:48
  • "_Maybe it's not appropriate to compare Java and C++ in this way_" IMO it **is** appropriate to do that because if you work for a company that writes software as a service, the technology should be chosen on the requirements. Knowing differences between Java and C++ does have an influence in the decision process. And, don't you mean `initializer_list` (missing an `r`) ? Or my C++ knowledge is wrong. – KarelG Nov 15 '19 at 08:50
  • `stream is not verbose` :/ – Vishwa Ratna Nov 15 '19 at 08:51
  • https://stackoverflow.com/a/16194967/8914226 –  Nov 15 '19 at 08:58

0 Answers0