本例子使用Java基于数组ArrayList简单实现HashMap的get和put功能
public class ArrayListHashMap<K,V> {
private List<Entry<K,V>> entries=new ArrayList<>(1000);
class Entry<K,V>{
K k;
V v;
public Entry(K k, V v) {
this.k = k;
this.v = v;
}
}
public void put(K k,V v){
entries.add(new Entry<>(k,v));
}
public V get(K k){
for (Entry entry:entries){
if(entry.k.equals(k)){
return (V) entry.v;
}
}
return null;
}
public static void main(String[] args) {
ArrayListHashMap<String,String> arrayListHashMap =new ArrayListHashMap<>();
arrayListHashMap.put("sa","1");
System.out.println(arrayListHashMap.get("sa"));
}
}
这种方式的查询效率低,为O(n)