2016-12-30 22:22:39 -08:00
|
|
|
// collectiontopics/ReadOnly.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Using the Collections.unmodifiable methods
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
2015-11-11 20:20:04 -08:00
|
|
|
import onjava.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
public class ReadOnly {
|
|
|
|
static Collection<String> data =
|
|
|
|
new ArrayList<>(Countries.names(6));
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Collection<String> c =
|
|
|
|
Collections.unmodifiableCollection(
|
|
|
|
new ArrayList<>(data));
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(c); // Reading is OK
|
2015-12-18 11:28:19 -08:00
|
|
|
//- c.add("one"); // Can't change it
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
List<String> a = Collections.unmodifiableList(
|
|
|
|
new ArrayList<>(data));
|
|
|
|
ListIterator<String> lit = a.listIterator();
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(lit.next()); // Reading is OK
|
2015-12-18 11:28:19 -08:00
|
|
|
//- lit.add("one"); // Can't change it
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
Set<String> s = Collections.unmodifiableSet(
|
|
|
|
new HashSet<>(data));
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(s); // Reading is OK
|
2015-12-18 11:28:19 -08:00
|
|
|
//- s.add("one"); // Can't change it
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
// For a SortedSet:
|
2017-01-22 16:48:11 -08:00
|
|
|
Set<String> ss =
|
|
|
|
Collections.unmodifiableSortedSet(
|
|
|
|
new TreeSet<>(data));
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2017-01-22 16:48:11 -08:00
|
|
|
Map<String,String> m =
|
|
|
|
Collections.unmodifiableMap(
|
|
|
|
new HashMap<>(Countries.capitals(6)));
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(m); // Reading is OK
|
2015-12-18 11:28:19 -08:00
|
|
|
//- m.put("Ralph", "Howdy!");
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
// For a SortedMap:
|
|
|
|
Map<String,String> sm =
|
|
|
|
Collections.unmodifiableSortedMap(
|
|
|
|
new TreeMap<>(Countries.capitals(6)));
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2017-05-10 11:45:39 -06:00
|
|
|
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO,
|
|
|
|
BURUNDI]
|
2015-06-15 17:47:35 -07:00
|
|
|
ALGERIA
|
2017-05-10 11:45:39 -06:00
|
|
|
[BENIN, BOTSWANA, ANGOLA, BURKINA FASO, ALGERIA,
|
|
|
|
BURUNDI]
|
2015-06-15 17:47:35 -07:00
|
|
|
{BENIN=Porto-Novo, BOTSWANA=Gaberone, ANGOLA=Luanda,
|
|
|
|
BURKINA FASO=Ouagadougou, ALGERIA=Algiers,
|
|
|
|
BURUNDI=Bujumbura}
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|