//: containers/ReadOnly.java // ©2015 MindView LLC: see Copyright.txt // Using the Collections.unmodifiable methods. import java.util.*; import net.mindview.util.*; import static net.mindview.util.Print.*; public class ReadOnly { static Collection data = new ArrayList<>(Countries.names(6)); public static void main(String[] args) { Collection c = Collections.unmodifiableCollection( new ArrayList<>(data)); print(c); // Reading is OK //! c.add("one"); // Can't change it List a = Collections.unmodifiableList( new ArrayList<>(data)); ListIterator lit = a.listIterator(); print(lit.next()); // Reading is OK //! lit.add("one"); // Can't change it Set s = Collections.unmodifiableSet( new HashSet<>(data)); print(s); // Reading is OK //! s.add("one"); // Can't change it // For a SortedSet: Set ss = Collections.unmodifiableSortedSet( new TreeSet<>(data)); Map m = Collections.unmodifiableMap( new HashMap<>(Countries.capitals(6))); print(m); // Reading is OK //! m.put("Ralph", "Howdy!"); // For a SortedMap: Map sm = Collections.unmodifiableSortedMap( new TreeMap<>(Countries.capitals(6))); } } /* Output: [ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] ALGERIA [ANGOLA, ALGERIA, BURKINA FASO, BENIN, BURUNDI, BOTSWANA] {ANGOLA=Luanda, ALGERIA=Algiers, BURKINA FASO=Ouagadougou, BENIN=Porto-Novo, BURUNDI=Bujumbura, BOTSWANA=Gaberone} *///:~