package cn.sxt.mycollection;
import java.util.HashMap;
/**
* 手动实现HashSet简单原理
* @author Administrator
*
*/
public class SxtHashSet<E> {
HashMap map;
private static final Object PRESENT=null;
public SxtHashSet() {
map=new HashMap();
}
public void add(E o) {
map.put(o,PRESENT);
}
public int size() {
return map.size();
}
@Override
public String toString() {
StringBuilder sb=new StringBuilder("[");
for(Object key:map.keySet()) {
sb.append(key+",");
}
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}
public static void main(String[] args) {
SxtHashSet<Object> set=new SxtHashSet<>();
set.add("aaa");
set.add(1234);
set.add("bbb");
set.add(5+6);
set.add("ccc");
System.out.println(set);
}
}
/**
* set:无序,不可重复
* list:有序,可重复
*
*/
输出结果:
[aaa,1234,ccc,bbb,11]