特点
- 存放键值对
- 根据键对象找到对应的值对象
- 键不能重复
继承关系图
- hashmap:效率高,线程不安全
- hashtable:线程安全,效率低
底层实现
数组加链表
map(映射)接口
Entry(条目)
class SxtEntry {
Object key;
Object value;
public SxtEntry() {
}
public SxtEntry(Object key, Object value) {
super();
this.key = key;
this.value = value;
}
public Object getKey() {
return key;
}
public void setKey(Object key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
实现
package cn.bjsxt.collection;
import java.util.LinkedList;
public class SxtMap {
// 链表对象数组
LinkedList[] arr = new LinkedList[990];
// 容量
int size;
public void put(Object key, Object value) {
SxtEntry e = new SxtEntry(key, value);
int hash = key.hashCode();
hash = hash < 0 ? -hash:hash;
int a = hash%arr.length;
if(arr[a]==null) {
// 链表对象
LinkedList list = new LinkedList();
arr[a] = list;
list.add(e);
}else {
LinkedList list = arr[a];
// 处理重复键值
for(int i1=0;i1<list.size();i1++) {
SxtEntry e2 = (SxtEntry) list.get(i1);
// 相同key,则覆盖value
if(e2.key.equals(key)) {
e2.value = value;
e.value=value ;
return;
}
}
}
}
public Object get(Object key) {
int a = key.hashCode() % arr.length;
if(arr[a]!=null) {
LinkedList list = arr[a];
for(int i=0;i<list.size();i++) {
SxtEntry e = (SxtEntry) list.get(i);
if(e.key.equals(key)) {
return e.value;
}
}
}
return null;
}
//*
public boolean containsKey(Object key) {
for(int i=0;i<size;i++) {
if(arr[i].contains(key)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
SxtMap m = new SxtMap();
m.put(1, "aaa");
m.put(2, "aa");
m.put(3, "a");
String str = (String)m.get(3);
System.out.println(str);
}
}
小结
未完待续···(hashcode & equals)