Java Set接口

来源:互联网 发布:游戏客户端编程 编辑:程序博客网 时间:2024/06/07 06:36

说明:本文是阅读《Java程序性能优化》(作者:葛一明)一书中关于Set接口一节的笔记。


一、Set接口

1、Set接口并没有在Collection接口之上增加额外的操作。Set集合中的元素是不能重复的。有关Set接口的类图如下:仔细一看,Set接口的相关类图结构与Map接口的相关类图结构挺相似的。所以其实只要熟悉了Java Map接口,对Set接口就比较容易理解了。其实所有这些Set的实现,都只是对应的Map的一种封装而已,比如HashSet是对HashMap的封装,所以有关HashSet的一切特性和实现细节与HashMap完全相同。以此类推,LinkedHashSet对应LinkedHashMap,TreeSet对应TreeMap。


2、以HashSet为例,其内部维护了一个HashMap对象,并将所有有关Set的实现,都委托给HashMap对象完成。比如下面的HashSet的add方法的实现:

/** * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * this set contains no element <tt>e2</tt> such that * <tt>(e==null ? e2==null : e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */public boolean add(E e) {return map.put(e, PRESENT)==null;}

0 0
原创粉丝点击