Libraryless. Click here for Pure Java version (3554L/19K).
1 | // Maximally compact implementation of such a thing |
2 | // Use SortedArrayBasedMap instead if keys are sortable |
3 | sclass MinimalMap<A, B> extends CompactAbstractMap<A, B> { |
4 | O[] entries; |
5 | |
6 | *() {} |
7 | *(Map<A, B> map) { |
8 | if (empty(map)) ret; |
9 | entries = new O[l(map)*2]; |
10 | int i = 0; |
11 | for (A a, B b : map) { |
12 | entries[i++] = a; |
13 | entries[i++] = b; |
14 | } |
15 | } |
16 | |
17 | public int size() { ret l(entries)/2; } |
18 | public Set<Map.Entry<A, B>> entrySet() { |
19 | ret toLinkedHashMap().entrySet(); |
20 | } |
21 | |
22 | int find(O o) { |
23 | if (entries != null) |
24 | for (int i = 0; i < entries.length; i += 2) |
25 | if (eq(entries[i], o)) |
26 | ret i; |
27 | ret -1; |
28 | } |
29 | |
30 | public bool containsKey(O o) { |
31 | ret find(o) >= 0; |
32 | } |
33 | |
34 | @Override |
35 | public B get(O o) { |
36 | int i = find(o); |
37 | ret i >= 0 ? (B) entries[i+1] : null; |
38 | } |
39 | |
40 | LinkedHashMap<A, B> toLinkedHashMap() { |
41 | new LinkedHashMap<A, B> map; |
42 | if (entries != null) |
43 | for (int i = 0; i < entries.length; i += 2) |
44 | map.put((A) entries[i], (B) entries[i+1]); |
45 | ret map; |
46 | } |
47 | |
48 | @Override |
49 | public B put(A key, B value) { |
50 | int i = find(key); |
51 | |
52 | // existing key? |
53 | if (i >= 0) { |
54 | B oldValue = (B) entries[i+1]; |
55 | entries[i+1] = value; |
56 | ret oldValue; |
57 | } |
58 | |
59 | // new key |
60 | int l = l(entries); |
61 | entries = resizeObjectArray(entries, l+2); |
62 | entries[l] = key; |
63 | entries[l+1] = value; |
64 | null; |
65 | } |
66 | |
67 | @Override |
68 | public B remove(O key) { |
69 | int i = find(key); |
70 | if (i < 0) null; |
71 | B oldValue = (B) entries[i+1]; |
72 | int l = l(entries); |
73 | entries = spliceObjectArray(entries, i, l+2, null); |
74 | ret oldValue; |
75 | } |
76 | } |
Began life as a copy of #1030858
download show line numbers debug dex old transpilations
Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt
No comments. add comment
Snippet ID: | #1031042 |
Snippet name: | MinimalMap - map consisting just of an unordered object array [O(n) access/put/remove] |
Eternal ID of this version: | #1031042/13 |
Text MD5: | f7c46e86c95a8a8b56892e635e2e793a |
Transpilation MD5: | 7109e2bf87e9ac69633c54366c495066 |
Author: | stefan |
Category: | javax |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2021-07-16 06:36:30 |
Source code size: | 1706 bytes / 76 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 199 / 429 |
Version history: | 12 change(s) |
Referenced in: | [show references] |