#How do lists work in java

1 messages · Page 1 of 1 (latest)

burnt thistle
#
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> list2 = List.of(1, 2, 3, 4, 5);

What is the difference? Can I index this list? How do I remove/add items to it?

paper terraceBOT
#

<@&987246399047479336> please have a look, thanks.

potent sparrow
#

note that List.of returns an unmodifiable list

#

so you cant add/remove

#

Arrays.asList returns a modifiable list instead

#

though its fixed size

burnt thistle
burnt thistle
#

and can I have a list/array of strings?

tired stump
#

or repeated .add calls

modest robin
feral flint
#

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.

modest robin
#

@burnt thistle

tired stump
#

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

modest robin
modest robin
tired stump
#

List.of doesn't allocate an array

modest robin
#

and an array

#

since it's an immutable list

#

it needs to copy the vararg array

#

it can't trust it

tired stump
#

it uses a method called listFromTrustedArray

#

so List.of allocates an array then arraylist copies it

modest robin
#

Oh, that's why it has overloads

#

alright, so it's equivalent for the non vararg overloads

feral flint
#

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.

brittle vortex
#

Arrays.asList is fixed-size, wouldnt work if they need a dynamically sized list

#

ohhh

#

using Arrays.asList instead of List.of

#

my bad

feral flint
#

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.

burnt thistle
#

@modest robin

elder agate
burnt thistle
#

How?

elder agate
#

List<String> someList = new ArrayList<>();