61 lines
2.2 KiB
Java
Raw Normal View History

2016-12-30 22:22:39 -08:00
// collectiontopics/Unsupported.java
// (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
// Unsupported operations in Java collections
2015-06-15 17:47:35 -07:00
import java.util.*;
public class Unsupported {
2017-01-22 16:48:11 -08:00
static void
check(String description, Runnable tst) {
2017-01-08 22:55:49 -08:00
try {
tst.run();
} catch(Exception e) {
System.out.println(description + "(): " + e);
}
}
2015-06-15 17:47:35 -07:00
static void test(String msg, List<String> list) {
System.out.println("--- " + msg + " ---");
Collection<String> c = list;
Collection<String> subList = list.subList(1,8);
// Copy of the sublist:
Collection<String> c2 = new ArrayList<>(subList);
2017-01-08 22:55:49 -08:00
check("retainAll", () -> c.retainAll(c2));
check("removeAll", () -> c.removeAll(c2));
check("clear", () -> c.clear());
check("add", () -> c.add("X"));
check("addAll", () -> c.addAll(c2));
check("remove", () -> c.remove("C"));
2015-06-15 17:47:35 -07:00
// The List.set() method modifies the value but
// doesn't change the size of the data structure:
2017-01-08 22:55:49 -08:00
check("List.set", () -> list.set(0, "X"));
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
List<String> list = Arrays.asList(
"A B C D E F G H I J K L".split(" "));
2015-06-15 17:47:35 -07:00
test("Modifiable Copy", new ArrayList<>(list));
test("Arrays.asList()", list);
test("unmodifiableList()",
2016-01-25 18:05:55 -08:00
Collections.unmodifiableList(
new ArrayList<>(list)));
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
--- Modifiable Copy ---
--- Arrays.asList() ---
retainAll(): java.lang.UnsupportedOperationException
removeAll(): java.lang.UnsupportedOperationException
clear(): java.lang.UnsupportedOperationException
add(): java.lang.UnsupportedOperationException
addAll(): java.lang.UnsupportedOperationException
remove(): java.lang.UnsupportedOperationException
--- unmodifiableList() ---
retainAll(): java.lang.UnsupportedOperationException
removeAll(): java.lang.UnsupportedOperationException
clear(): java.lang.UnsupportedOperationException
add(): java.lang.UnsupportedOperationException
addAll(): java.lang.UnsupportedOperationException
remove(): java.lang.UnsupportedOperationException
List.set(): java.lang.UnsupportedOperationException
2015-09-07 11:44:36 -06:00
*/