A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

Set

© 李俊豪 中级黑马   /  2012-11-5 17:57  /  1157 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 李俊豪 于 2012-11-6 21:24 编辑

Set里的元素是不能重复的,那么用什么方法来区分重复与否呢?

点评

请仔细看毕老师的视频  发表于 2012-11-5 19:37

2 个回复

倒序浏览
问的太笼统了。或者说意义不明。

基本集合类都有自己的方法来辨认是否有重复数值,直接调用就行。再不行就用这个储存的值去遍历集合里所有的内容对比是否产生重复,是就丢弃,否就add.

评分

参与人数 1技术分 +1 收起 理由
邓艳秋 + 1

查看全部评分

回复 使用道具 举报
这种问题的最好解决办法,就是查看一下JDK源码来解决你的疑惑:我们先看一下,set集合的一个具体实现类:HashSet,其中的add(E e)方法的源码如下:
  1. /**
  2. * Adds the specified element to this set if it is not already present.
  3. * More formally, adds the specified element <tt>e</tt> to this set if
  4. * this set contains no element <tt>e2</tt> such that
  5. * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
  6. * If this set already contains the element, the call leaves the set
  7. * unchanged and returns <tt>false</tt>.
  8. *
  9. * @param e element to be added to this set
  10. * @return <tt>true</tt> if this set did not already contain the specified
  11. * element
  12. */
  13. public boolean add(E e) {
  14. return map.put(e, PRESENT)==null;
  15. }
复制代码
显然HashSet在添加元素的时候,使用的是一个HashMap<E,Object> map结构集合去存储,那么我们就去HashMap中找到put方法是如何实现的就知道是如何解决的了,代码如下:
  1. public V put(K key, V value) {
  2. if (key == null)
  3. return putForNullKey(value);
  4. int hash = hash(key.hashCode());
  5. int i = indexFor(hash, table.length);
  6. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  7. Object k;
  8. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  9. V oldValue = e.value;
  10. e.value = value;
  11. e.recordAccess(this);
  12. return oldValue;
  13. }
  14. }

  15. modCount++;
  16. addEntry(hash, key, value, i);
  17. return null;
  18. }
复制代码
看到这些代码,也许你就会明白,如何实现去除重复元素了,我们在hashset中加入元素的时候,是判断当前值的hash值与集中合的元素的hash值进行比较,如果相同,则不会向集合中添加新元素,而只是对原来有的元素进行修改。就讲到这里吧,希望对你有帮助

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 很给力!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马