public class HashMap { //存储元素数组 private Entry[] entry = null; //记录map个数 private int size; //构造器 public HashMap() { this.entry = new Entry[10]; } //增加新元素 public void put(Object key, Object value) { Entry e = new Entry(key, value); //增加哈希算法 int index=key.hashCode() % 10; entry[index] = e; size++; } //获取元素 public Object get(Object key) { //增加哈希算法 int index=key.hashCode() % 10; Entry e = entry[index]; return e.getValue(); } @Override public String toString() { StringBuilder sb=new StringBuilder(); sb.append("["); for(int i=0;i<entry.length -1;i++) { Entry e = entry[i]; if(e != null) { sb.append(e.getValue()); } else { sb.append("null"); } if(i != entry.length-1) { sb.append(","); } } sb.append("]"); return sb.toString(); } }
测试代码
public class Demo { /*** * 简单的 put get方法 * @param args */ public static void main(String[] args) { HashMap map=new HashMap(); map.put("刘诗华", "罗兰"); System.out.println(map);// [null,罗兰,null,null,null,null,null,null,null,] Object s = map.get("刘诗华"); System.out.println(s); //罗兰 } }