自定义HashSet
程序员文章站
2022-05-13 23:51:41
...
HashSet其实就是简化版的HashMap
import java.util.HashMap;
/**
* 自定义HashSet其实就是简化版的HashMap
* @author Administrator
*
*/
public class MyHashSet00 {
HashMap map;
private final Object PRESENT = new Object();
public MyHashSet00() {
map = new HashMap();
}
public void add(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) {
MyHashSet00 s = new MyHashSet00();
s.add("aaa");
s.add("bbb");
s.add("ccc");
System.out.println(s);
}
}
上一篇: HashSet解析
下一篇: 【java基础】HashSet源码分析