Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8177290

add copy factory methods for unmodifiable List, Set, Map

    XMLWordPrintable

Details

    Description

      Probably something like this on List:

          static <T> List<T> copyOf(Collection<? extends T> coll)

      This would return an unmodifiable List. There would be similar factory methods for Set and Map. This would be implemented the obvious way for most cases.

      In addition, this could check the implementation of the collection being copied from, and if it's a class that's known to be immutable, it would simply return that reference.

      This would be a shallow copy.

      This would also allow variant aliasing of collections, which generally isn't permitted. For example,

          List<String> list = List.of(...);
          List<CharSequence> newList = List.copyOf(list);

      This can't be done for mutable collections, since it can lead to heap pollution. Since these implementations are unmodifiable, this should be safe.

      Short-circuiting of copying is one of the oft-cited use cases for exposing immutable collection types. It's also one of the reasons people sometimes ask for a test method that returns whether the collection is or isn't unmodifiable. The copy factories could help mitigate some of the demand for those mechanisms.

      Attachments

        Issue Links

          Activity

            People

              smarks Stuart Marks
              smarks Stuart Marks
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: