public class LinkedList<Key,Value> {
private Node first;
private class Node {
Key key;
Value val;
Node next;
public Node(Key key, Value val, Node next) {
this.key = key;
this.val = val;
this.next = next;
}
}
public Value get(Key key) {
for (Node x = first; x != null;x = x.next) {
if (key.equals(x.key)) return x.val;
}
return null;
}
public void put(Key key, Value val) {
for (Node x = first; x != null;x = x.next) {
if (key.equals(x.key)) {
x.val = val;
return;
}
}
first = new Node(key,val,first); // 从头部加入新节点
}
}
public class HashTree <Key,Value>{ //泛型
private int Num;
private int capacity;
private LinkedList<Key,Value>[] ht;
public HashTree() {
this(1);
}
public HashTree(int capacity) {
ht = (LinkedList<Key,Value>[]) new LinkedList[capacity];
this.capacity = capacity;
for (int i =0;i < capacity;i++)
ht[i] = new LinkedList<Key,Value>();
}
private int hash(Key key) {
return (key.hashCode() & 0x7ffffffff) % capacity;
}
public Value get(Key key) {
return ht[ hash(key)].get(key);
}
public void put(Key key, Value value) {
Num++;
ht[hash(key)].put(key,value);
}
}
public class AnotherHashTree <Key,Value>{ //泛型
private int Num;
private int capacity;
private Value[] values;
private Key[] keys;
public AnotherHashTree() {
this(1);
}
public AnotherHashTree(int capacity) {
values = (Value[]) new Object[capacity];
keys = (Key[]) new Object[capacity];
}
private int hash(Key key) {
return (key.hashCode() & 0x7ffffffff) % capacity;
}
public Value get(Key key) {
int i =hash(key);
while (keys[i] != null) {
if (keys[i].equals(key) ) return values[i]; //用equal比用=要好,因为有的类型可能不能直接比较
else i = (i+1) % capacity;
}
return null;
}
public void put(Key key, Value value) {
int i = hash(key);
while (keys[i] != null && !keys[i].equals(key)) i = (i+1) %capacity;
keys[i] = key;
values[i] = value;
Num++;
if(Num > capacity/2) resize(2*capacity);
}
private void resize(int capacity) {
AnotherHashTree<Key,Value> temp =new AnotherHashTree<Key,Value>(capacity);
for (int i = 0;i<capacity;i++) {
temp.put(keys[i],values[i]);
}
this.keys = temp.keys;
this.values = temp.values;
this.capacity = temp.capacity;
}
}