-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathMapCheat.java
More file actions
113 lines (84 loc) · 2.7 KB
/
MapCheat.java
File metadata and controls
113 lines (84 loc) · 2.7 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
107
108
109
110
111
112
113
/*
# Map
Interface.
Major implementations include `HashMap` and `TreeMap`,
both of which inherit `AbstractMap`.
*Not* a collection:
http://stackoverflow.com/questions/2651819/why-doesnt-java-map-extends-collection
# TreeMap
Implements `Map`.
Javadoc says it's a red-black tree.
You can use a custom comparator to compare the entries without wrapping the key.
# HashMap
Implements `Map`.
You cannot use a custom hash function without wrapping the key:
http://stackoverflow.com/questions/5453226/java-need-a-hash-map-where-one-supplies-a-function-todo-the-hashing
# HashTable
Like `HashMap` but synchronized.
# EnumMap
Only for enum keys.
TODO why is it faster?
*/
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MapCheat {
public static void main(String[] args) {
// Basic usage.
{
Map<Integer,String> m = new TreeMap<>();
m.put(0, "zero");
m.put(1, "one");
assert m.get(0).equals("zero");
assert m.get(1).equals("one");
assert m.get(2) == null;
}
/*
# put
Returns the previous value for the key, null if none.
*/
{
Map<Integer,Integer> m = new TreeMap<>();
assert m.put(0, 0) == null;
assert m.put(0, 1).equals(0);
assert m.put(0, 2).equals(1);
//assert(m.put(1, 1).equals(1));
}
/*
# entrySet
# Iterate over map
http://stackoverflow.com/questions/46898/iterate-over-each-entry-in-a-map
In Java 8, there is also the `forEach` loop version.
*/
{
//for (Map.Entry<String, String> entry : map.entrySet()) {
//System.out.println(entry.getKey() + "/" + entry.getValue());
//}
/*
The entrySet is backed by the map. Modifications to it modify the map.
*/
{
Map<Integer,Integer> m = new TreeMap<>();
assert m.put(1, -1) == null;
assert m.put(2, -2) == null;
Set<Integer> entrySet = m.keySet();
Iterator<Integer> it = entrySet.iterator();
while (it.hasNext())
if (it.next() == 1)
it.remove();
assert m.get(2) == -2;
assert m.size() == 1;
}
}
/*
# values
Collection of the values. Not a copy.
Not a set because there can be duplicates.
*/
/*
# keySet
Set of all the keys.
*/
}
}