3 ms·
When he says the new collections syntax creates immutable collections, does that mean modifying them creates a copy, or that objects in the collection can't be
by paulbaumgart 17y ago
When he says the new collections syntax creates immutable collections, does that mean modifying them creates a copy, or that objects in the collection can't be added/changed at all?
- hello_moto 17y agoI think he meant adding a new item would create a new list. Which makes working with operation expensive but a bit safer.
- akronim 17y agoYou can't add items to immutable collections - if you call add() etc you'll get an UnsupportedOperationException. If you want a mutable version then you need to create a new collection, and can use the immutable collection to provide the starting values, like this: Set<String> mutable = new HashSet<String>(immutable)
- paulbaumgart 17y agoOh, but you can still do: List<String> list = new ArrayList<String>(); list.add("item"); String item = list[0]; right? I guess I was thrown off by the wording- I assumed the line about collections being immutable applied to all collections that use the new syntax.
- JulianMorrison 17y agoWhich is madness that completely misses the point of proper immutable collections (Clojure style) - that you can "modify" them, by creating a new copy with the thing added, and it shares storage with the original and the copying isn't as slow as a copy-by-clone. The first thing people are going to do with these half assed immutable collections is pour the contents out into a mutable container. Which completely obviates all the thread safety and whatnot. I slap my forehead. Do these people have no sense?
- lmkg 17y agoIs the addition of immutable structures going to push the JVM towards more optimization for immutable structures in any way? I ask because of Clojure, not Java itself.