This will be a method that generates a List view of the array argument, similar to Arrays.asList(). The difference is that the requested method will create an unmodifiable view of the array, which is faster than an immutable view like ImmutableList. (It copies the array) This method would be a single wrapper instead of a double wrapper like this:
Collections.unmodifiableList(Arrays.asList(new Object{}));
And the one above is long enough for us to create a shortcut for it.
@liach - what is the difference between unmodifiableList and immutable one?
In both cases you would like to have a list that cannot be modified - i.e - have elements added or removed from it
UnmodifableList's backing list can be modified, and the unmodifiable version can reflect that change.
ImmutableList is immutable, that is it can never be modified.
List<String> list = Lists.newArrayList("apple", "banana");
List<String> view = Collections.unmodifiableList(list);
view.forEach(System.out::println);
System.out.println(); //to separate two outputs
list.set(1, "pear");
view.forEach(System.out::println);
The expected output should be:
banana
apple
pear
@liach so you would like to retrieve an unmodifiable list, which is backed by an array?
Yes, and it should be as light as possible
I would prefer not to have an interim allocation of Arrays.asList , but simply have
the array, and return an umodifiable list that is backed by it (I refer to the example you gave - I feel Arrays.asList is an unnecessary allocation).
I would like to work on a patch for this -
My idea is to return an object implementing the list interface, and throwing an exception on the methods that modify the list (i.e - add).
What do you think?
Yes. Generally something like Arrays.ArrayList but does not support set(int index, E element) operation.
Thanks @liach , i will be glad to contribute the patch.
Hi @yairzaslavsky, I'd recommend you wait until someone on Guava team replies back to this issue before writing your patch. This is because on the Contributing page, it explicitly states that API additions will only be considered after a lengthy and thorough review process, and so if your write the code now, it may be all for nought.
@jbduncan I have read it, but thanks for pointing it out to me.
For me it's easier sometimes to express myself via code. I am perfectly fine with the possibility the idea gets rejects. A pull request, even if not perfect, can show what we had in mind.
This convenience sounds great for a project's utilities but not common enough for Guava to add it. We generally prefer people to use Lists from the getgo anyway over an array.
Thanks for the reply!
Most helpful comment
@jbduncan I have read it, but thanks for pointing it out to me.
For me it's easier sometimes to express myself via code. I am perfectly fine with the possibility the idea gets rejects. A pull request, even if not perfect, can show what we had in mind.