根据hashset的源码可知,其底层是由HashMap来实现的
根据源码仿写set
package sxt.gaoqi.container;
import java.util.HashMap;
import java.util.Map;
public class JsHashSet
{
Map map;
private static final Object PRESENT = new Object();
public JsHashSet()
{
map = new HashMap();
}
public int size()
{
return map.size();
}
public void add(Object o)
{
map.put(o, map);
}
@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)
{
JsHashSet set = new JsHashSet();
set.add("a");
set.add("b");
set.add("c");
set.add("a");
System.out.println(set);
}
}