I do wonder if a simple unmodifiable and/or immutable marker-interface could help out (a la RandomAccess).
This would provide a convention (implemented consistently in JDK types) for applications to bypass defensive copying when you may have types that are not in the JDK, but can have these properties (though you might do defensive copying anyway in security contexts to prevent fibbing about it, and undermining trust).
The JDK has some scenarios where it can opt out of copying because of the special knowledge of internal types, but it misses in far too many cases (and it's a tool only the JDK can use).
You actually don't need that. If you look at copyOf implementation, it already detects its internal unmodifiable wrapper and then just passes it back out if it's already that. So, feel free to defensively copyOf as much as you want!
Now, if you're talking about some sort of universal JDK feature, then that would be a different beast.
I was acknowledging that behaviour already - but it only works for unmodifiable types inside the JDK. Those aren't the only Collection implementations - and it doesn't support the Collections.unmodifiableList(...) wrappers.
At the moment we see a lot of unwanted and unnecessary list-copying. It would be good for the developer to be able to express that this list is safe to skip defensive copies without having to make a copy with List.of (paying a toll every time just in case the list might be passed to someone who wants the safety of a stable list)
View all comments
Show parent comment
1
u/8igg7e5 Feb 05 '26
I do wonder if a simple
unmodifiableand/orimmutablemarker-interface could help out (a laRandomAccess).This would provide a convention (implemented consistently in JDK types) for applications to bypass defensive copying when you may have types that are not in the JDK, but can have these properties (though you might do defensive copying anyway in security contexts to prevent fibbing about it, and undermining trust).
The JDK has some scenarios where it can opt out of copying because of the special knowledge of internal types, but it misses in far too many cases (and it's a tool only the JDK can use).
Essentially supporting this across more types: