forked from cirosantilli/java-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionsCheat.java
More file actions
106 lines (76 loc) · 2.96 KB
/
CollectionsCheat.java
File metadata and controls
106 lines (76 loc) · 2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
# Collections
Static methods that do operations on classes that implement `Collection`.
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
Some methods however require subintefaces of `Collection`, e.g. `sort` requires `List`,
because `Collections` are not necessarily ordered, but `List` is.
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class CollectionsCheat {
public static void main(String[] args) {
/*
# sort Collections
Sort a collection inplace.
It's contents must implement `Comparable`.
The Javadoc says it's a mergesort similar to Python's.
*/
{
List<Integer> l = new ArrayList<>();
l.add(2);
l.add(0);
l.add(1);
List<Integer> l2 = new ArrayList<>();
l2.add(0);
l2.add(1);
l2.add(2);
// Returns void
Collections.sort(l);
assert l.equals(l2);
}
/*
# unmodifiableCollection
# unmodifiableSet
# unmodifiableMap
# unmodifiableList
As of JDK9, those methods are implemented by returning private inner classes
that override the modifier methods to throw and exception:
http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/f08705540498/src/java.base/share/classes/java/util/Collections.java#l4746
# TODO how exactly does that work, considering that it just returns a List?
Is there a UnmodifiableList class, or is it just some private implementation of it that gets returned?
Note that `Collections#unmodifiableCollection` gives you an unmodifiable collection.
Guava however does seem to have public immutable collections:
<http://stackoverflow.com/questions/5611324/whats-the-difference-between-collections-unmodifiableset-and-immutableset-of>
*/
{
Collection<Integer> c = new ArrayList<>();
Collection<Integer> c2 = Collections.unmodifiableCollection(c);
boolean fail = false;
try {
c2.add(1);
} catch(UnsupportedOperationException e) {
fail = true;
}
assert fail;
}
/*
# emptySet
# emptyList
# emptyMap
# singleton
# singletonList
# singletonMap
Create immutable collections that contain one or 0 elements.
TODO what is the main application? Just reducing the abilities of the method that gets called?
<http://stackoverflow.com/questions/4801794/use-of-javas-collections-singletonlist>
# nCopies
ImmutablelList with n copies of a given reference.
All elements are a single reference.
Only works for objects.
*/
{
}
}
}