HashSet的底层其实就是HashMap,换句话说HashSet就是简化版的HashMap。
直接上代码:
package com.xzlf.collection2;
import java.util.HashMap;
public class MyHashSet<E> {
HashMap<E, Object> map;
private static final Object PRESENT = new Object();
public MyHashSet() {
map = new HashMap<E, Object>();
}
public void add(E key) {
map.put(key, PRESENT);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (E k : map.keySet()) {
sb.append(k + ",");
}
sb.setCharAt(sb.length() - 1, ']');
return sb.toString();
}
public static void main(String[] args) {
MyHashSet<String> set = new MyHashSet<String>();
set.add("aa");
set.add("bb");
set.add("cc");
System.out.println(set);
}
}
运行测试: