有一段代码HashSet h = new HashSet(arlList); 
   arlList.clear(); 
   arlList.addAll(h); 
arlList是一个ArrayList
为什么运行了上面代码后就可以去除其中重复的值,不是很明白,求解释

解决方案 »

  1.   

    好象HashSet的有數據是不能重復的
      

  2.   

    HashSet是不能重复数据的,这个还有解释,自己看API吧
      

  3.   

    自己去看HashSet的源代码,
    这是HashMap的put的源代码; public V put(K key, V value) {
            if (key == null)
                return putForNullKey(value);
            int hash = hash(key.hashCode());
            int i = indexFor(hash, table.length);
            for (Entry<K,V> e = table[i]; e != null; e = e.next) {
                Object k;
                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                    V oldValue = e.value;
                    e.value = value;
                    e.recordAccess(this);
                    return oldValue;
                }
            }        modCount++;
            addEntry(hash, key, value, i);
            return null;
        }HashSet里面的add方法就是调用的这个方法,自己看看什么都明白了
      

  4.   

    请翻书...
    set接口不允许存储相同对象
    也就是equals / hashcode相同addAll函数遍历原集合,插入到新set中,自然就没有重复对象了
      

  5.   

    HashSet不允许重复元素,具体与底层实现有关。
      

  6.   

    clear方法清空arraylist中的元素;
    addall把set中的元素全都拷贝进arraylist中,set的元素没有重复的,所以arraylist中此时没有重复元素了
      

  7.   

    各位已经说的很详细了,建议lz把 list、map、collection等的异同点好好看看
      

  8.   

    本质简单来说就是对hashcode和eques的重写
      

  9.   

    你用了 Set, 建议你看看  new HashSet(arlList)的源码