How do I create a read-only collection?

John Zukowski

The Collections class has six methods to help out here:

  • unmodifiableCollection(Collection c)
  • unmodifiableList(List list)
  • unmodifiableMap(Map m)
  • unmodifiableSet(Set s)
  • unmodifiableSortedMap(SortedMap m)
  • unmodifiableSortedSet(SortedSet s)
If you then get an Iterator from one of these unmodifiable collections, when you call remove() it will throw an UnsupportedOperationException.