标签:move pre package 分享 aaa val img ++ static
一、背景:
package com.cy.collection; public class Wife { String name; public Wife(String name){ this.name = name; } @Override public String toString() { return "Wife [name=" + name + "]"; } }
Map.java:
package com.cy.collection; /** * 自定义实现Map */ public class Map { private Entry[] arr = new Entry[1000]; //这里暂时不考虑扩容 private int size; //这里都是private的,不暴露size属性 /** * 1.键不能重复,如果含有这个键,就替换value * @param key * @param value */ public void put(Object key, Object value){ for(int i=0; i<size; i++){ if(arr[i].key.equals(key)){ arr[i].value = value; return; } } arr[size++] = new Entry(key, value); } //根据key获取 public Object get(Object key){ for(int i=0; i<size; i++){ if(arr[i].key.equals(key)){ return arr[i].value; } } return null; } //根据key删除 public boolean remove(Object key){ boolean success = false; for(int i=0;i<size;i++){ if(arr[i].key.equals(key)){ success = true; remove(i); } } return success; } private void remove(int i){ int numMoved = size - i - 1; if(numMoved>0){ System.arraycopy(arr, i+1, arr, i, numMoved); } arr[--size] = null; //Let gc do its work } //containsKey public boolean containsKey(Object key){ for(int i=0; i<size; i++){ if(arr[i].key.equals(key)){ return true; } } return false; } //containsValue 同containsKey //size public int size(){ return size; } } /** * 用来存放键值对的条目 */ class Entry{ Object key; Object value; public Entry(Object key, Object value) { super(); this.key = key; this.value = value; } }
Test.java测试代码:
package com.cy.collection; public class Test { public static void main(String[] args) { Map map = new Map(); map.put("张三", new Wife("abc")); map.put("李四", new Wife("def")); map.put("王五", new Wife("ghi")); System.out.println(map.get("张三")); map.remove("李四"); System.out.println(map.size()); map.put("张三", new Wife("aaa")); System.out.println(map.get("张三")); System.out.println(map.containsKey("张三")); } } 输出: Wife [name=abc] 2 Wife [name=aaa] true
标签:move pre package 分享 aaa val img ++ static
原文地址:https://www.cnblogs.com/tenWood/p/9180541.html