JAVA—手写HashMap
Map接口
public interface Map {
void put(Object key,Object value);
Object get(Object key);
int size();
boolean isEmpty();
interface Entry{
Object getKey();
Object getValue();
}
}
Map类
public class HashMap implements Map {
static final int DEFAULT_INITIAL_CAPACITY = 16;
transient int size;
transient Entry[] table;
public HashMap() {
table = new Entry[DEFAULT_INITIAL_CAPACITY];
}
@Override
public void put(Object key, Object value) {
int hash = key.hashCode();
int index = hash % table.length;
if (table[index] == null){
table[index] = new Entry(key,value,null,hash);
size++;
}else {
Entry entry = table[index];
while (entry != null){
if (entry.hash == hash && entry.getKey().equals(key)){
entry.value = value;
return;
}
entry = entry.next;
}
table[index] = new Entry(key,value,table[index],hash);
size++;
}
}
@Override
public Object get(Object key) {
Entry e = null;
int hash = key.hashCode();
int index = hash % table.length;
if (table[index] != null){
Entry entry = table[index];
while (entry != null){
if (entry.hash == hash && entry.getKey().equals(key)){
e = entry;
break;
}
entry = entry.next;
}
}
return e == null ? null : e.getValue();
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
for (int i = 0;i < table.length;i++){
if (table[i] != null){
Entry entry = table[i];
while (entry != null){
sb.append(entry.key + "=" + entry.value + ",");
entry = entry.next;
}
}
}
if (size != 0){
sb.deleteCharAt(sb.length() - 1);
}
sb.append("}");
return sb.toString();
}
class Entry implements Map.Entry{
final Object key;
Object value;
Entry next;
int hash;
public Entry(Object key, Object value, Entry next, int hash) {
this.key = key;
this.value = value;
this.next = next;
this.hash = hash;
}
@Override
public Object getKey() {
return key;
}
@Override
public Object getValue() {
return value;
}
@Override
public String toString() {
return "Entry{" +
"key=" + key +
", value=" + value +
", next=" + next +
", hash=" + hash +
'}';
}
}
}