Libraryless. Click here for Pure Java version (3138L/17K).
1 | // -has fast nextElement() and prevElement() |
2 | // -design allows for more functions like reordering the list |
3 | // -is NOT more compact than LinkedHashSet (probably the opposite) |
4 | // (check out CompactLinkedHashSet for that) |
5 | sclass BetterLinkedHashSet<A> extends AbstractSet<A> { |
6 | Map<A, Entry<A>> entries = hashMap(); |
7 | Entry<A> head, tail; |
8 | |
9 | sclass Entry<A> { |
10 | A value; |
11 | Entry<A> prev, next; |
12 | } |
13 | |
14 | public bool add(A a) { |
15 | if (entries.containsKey(a)) false; |
16 | new Entry<A> n; |
17 | n.value = a; |
18 | n.prev = tail; |
19 | if (tail != null) tail.next = n; |
20 | tail = n; |
21 | if (head == null) head = n; |
22 | entries.put(a, n); |
23 | true; |
24 | } |
25 | |
26 | public bool remove(O a) { |
27 | ret remove(entries.get(a)); |
28 | } |
29 | |
30 | public bool remove(Entry<A> node) { |
31 | if (node == null) false; |
32 | if (node.next != null) node.next.prev = node.prev; else tail = node.prev; |
33 | if (node.prev != null) node.prev.next = node.next; else head = node.next; |
34 | entries.remove(node.value); |
35 | true; |
36 | } |
37 | |
38 | public int size() { ret entries.size(); } |
39 | |
40 | public ItIt<A> iterator() { |
41 | ret new ItIt<A> { |
42 | Entry<A> entry = head; |
43 | public bool hasNext() { ret entry != null; } |
44 | public A next() { |
45 | A a = entry.value; |
46 | entry = entry.next; |
47 | ret a; |
48 | } |
49 | }; |
50 | } |
51 | |
52 | public bool contains(O a) { |
53 | ret entries.containsKey(a); |
54 | } |
55 | |
56 | public A prevElement(A a) { |
57 | Entry<A> e = entries.get(a); |
58 | if (e == null || e.prev == null) null; |
59 | ret e.prev.value; |
60 | } |
61 | |
62 | public A nextElement(A a) { |
63 | Entry<A> e = entries.get(a); |
64 | if (e == null || e.next == null) null; |
65 | ret e.next.value; |
66 | } |
67 | } |
download show line numbers debug dex old transpilations
Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt
No comments. add comment
Snippet ID: | #1031507 |
Snippet name: | BetterLinkedHashSet - should use CompactLinkedHashSet instead |
Eternal ID of this version: | #1031507/9 |
Text MD5: | d0766c779d9abdc1afb93dc5e0d92060 |
Transpilation MD5: | 0e07c2daee7022cd030528153b2fbf3c |
Author: | stefan |
Category: | javax |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2021-08-11 14:38:14 |
Source code size: | 1686 bytes / 67 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 216 / 430 |
Version history: | 8 change(s) |
Referenced in: | [show references] |