手工实现hashset

package cn.study.lu.four;

import java.util.*;

/**
* 手工实现hashmap,加深理解底层原理
* @author Administrator
*
*/
public class MyHashSet {
HashMap map;
private static final Object PRESENT = new Object();



public MyHashSet() {
map = new HashMap();
}

public void put(Object o) {
map.put(o, PRESENT);
}

public int size() {
return map.size();
}

@Override
public String toString() {

StringBuilder sb = new StringBuilder();
sb.append("[");

for(Object key: map.keySet()) {
sb.append(key+",");
}

sb.setCharAt(sb.length()-1,']');

return sb.toString();
}

public static void main(String[] args) {
MyHashSet set = new MyHashSet();

set.put("aaa");
set.put("bbb");
set.put("ccc");
set.put("ddd");

System.out.println(set);
}
}

你可能感兴趣的:(手工实现hashset)