#How do lists work in java
1 messages · Page 1 of 1 (latest)
Detected code, here are some useful tools:
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = List.of(1, 2, 3, 4, 5);
<@&987246399047479336> please have a look, thanks.
note that List.of returns an unmodifiable list
so you cant add/remove
Arrays.asList returns a modifiable list instead
though its fixed size
ah I see
how do I make it mutable then? (add or remove unlimited amount of nums)
and can I have a list/array of strings?
new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
or repeated .add calls
Probably better to use Arrays.asList, slight optimisation
Yeah it's not having to copy the array into the new list (the asList wrapper is a fixed cost).
And while I bet it would be hard to spot in a profiling run, I agree that when two options are equally complex and obvious to the reader, the cheaper one is preferable.
@burnt thistle
err
wouldn't Arrays.asList always allocate an array?
i thought part of the idea of List.of was that if the actual impls were value instances they could maybe do a smarter optimization
-
Arrays.asList allocates an array
-
then new ArrayList copies it
Ending with one copy -
List.of allocates an array
-
then copy into an immutable list
-
then new ArrayList copies it
Ending with two copies
No matter the implementations, they still can't trust the vararg array
Only the jit could deduce that it can trust it, and I don't think there is such an optimisation
List.of doesn't allocate an array
It allocates a list
and an array
since it's an immutable list
it needs to copy the vararg array
it can't trust it
it uses a method called listFromTrustedArray
so List.of allocates an array then arraylist copies it
Oh, that's why it has overloads
alright, so it's equivalent for the non vararg overloads
trusted arrays can come from the internals of streams. In general it can't trust an array the user provides. Perhaps the vararg bridge uses the trusted path as well.
only if length < 3
Arrays.asList is fixed-size, wouldnt work if they need a dynamically sized list
ohhh
using Arrays.asList instead of List.of
my bad
Ahh so it's not a feature of the varargs bridge, they're literally calling the trusted path for up to ten elements, and then spilling over into copying the varargs for larger argument lists.
Hopefully John Rose gets more time to progress the frozen-arrays investigation. That would allow more of these internals to avoid copying.
Yes.
How?
List<String> someList = new ArrayList<>();