IntHashMap.java
1.47 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
package com.glsx.commonres.file;
public final class IntHashMap {
public final static int nullValue = 0;
final static class Entry {
Entry(int key, int value) {
this.key = key;
this.value = value;
this.next = null;
}
int key;
int value;
Entry next;
}
private final int mCapacity;
private final Entry[] mTables;
private int mCollision;
private int mSize;
public IntHashMap(int capacity) {
this.mCapacity = capacity;
this.mTables = new Entry[capacity];
}
public int get(int key) {
int h = key;
//h ^= (h >>> 20) ^ (h >>> 12);
//h = h ^ (h >>> 7) ^ (h >>> 4);
for(Entry p = mTables[h % mCapacity]; p != null; p = p.next) {
if( p.key == key)
return p.value;
}
return nullValue;
}
public int put(int key, int value) {
int h = key;
//h ^= (h >>> 20) ^ (h >>> 12);
//h = h ^ (h >>> 7) ^ (h >>> 4);
int n = h % mCapacity;
Entry p = mTables[n];
Entry prev = null;
while( p != null) {
if( p.key == key) {
int oldValue = p.value;
p.value = value;
return oldValue;
}
mCollision++;
//LogUtils.d(this.getClass().getName(), "Got collision for key:" + key +"," + p.key);
prev = p;
p = p.next;
}
p = new Entry(key, value);
if( prev != null)
prev.next = p;
else
mTables[n] = p;
mSize++;
return nullValue;
}
public int collision() {
return mCollision;
}
public int capacity() {
return mCapacity;
}
public int size() {
return mSize;
}
}