1 | package tuffy.util; |
2 | |
3 | import java.util.ArrayList; |
4 | import java.util.HashMap; |
5 | import java.util.Random; |
6 | |
7 | public class HashArray<T> { |
8 | ArrayList<T> list = new ArrayList<T>(); |
9 | HashMap<T, Integer> indices = new HashMap<T, Integer>(); |
10 | Random rand = new Random(); |
11 | |
12 | public int size = 0; |
13 | |
14 | public ArrayList<T> getList(){ |
15 | return list; |
16 | } |
17 | |
18 | public T getRandomElement(){ |
19 | return list.get(rand.nextInt(list.size())); |
20 | } |
21 | |
22 | public boolean contains(T e){ |
23 | return indices.containsKey(e); |
24 | } |
25 | |
26 | public void clear(){ |
27 | list.clear(); |
28 | indices.clear(); |
29 | size = 0; |
30 | } |
31 | |
32 | public boolean isEmpty(){ |
33 | return list.isEmpty(); |
34 | } |
35 | |
36 | public void add(T e){ |
37 | if(indices.containsKey(e)) return; |
38 | list.add(e); |
39 | indices.put(e, list.size() - 1); |
40 | size ++; |
41 | } |
42 | |
43 | public void removeIdx(int i){ |
44 | int ss = list.size(); |
45 | if(i < 0 || i >= ss) return; |
46 | indices.remove(list.get(i)); |
47 | if(i == ss-1){ |
48 | list.remove(i); |
49 | }else{ |
50 | T last = list.get(ss-1); |
51 | indices.put(last, i); |
52 | list.set(i, last); |
53 | list.remove(ss-1); |
54 | } |
55 | size --; |
56 | } |
57 | |
58 | public void removeObj(T e){ |
59 | if(!indices.containsKey(e)) return; |
60 | int i = indices.get(e); |
61 | removeIdx(i); |
62 | } |
63 | } |