49 lines
1.5 KiB
Java
Raw Normal View History

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