当前位置: 代码迷 >> J2EE >> 关于去除Arraylist中重复数据的疑问,该如何处理
  详细解决方案

关于去除Arraylist中重复数据的疑问,该如何处理

热度:84   发布时间:2016-04-22 02:03:20.0
关于去除Arraylist中重复数据的疑问
有一段代码
Java code
HashSet h = new HashSet(arlList);    arlList.clear();    arlList.addAll(h); 

arlList是一个ArrayList
为什么运行了上面代码后就可以去除其中重复的值,不是很明白,求解释

------解决方案--------------------
好象HashSet的有數據是不能重復的
------解决方案--------------------
HashSet是不能重复数据的,这个还有解释,自己看API吧
------解决方案--------------------
自己去看HashSet的源代码,
这是HashMap的put的源代码;
Java code
 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的源代码,
这是HashMap的put的源代码;
Java code

public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
in……

------解决方案--------------------
请翻书...
set接口不允许存储相同对象
也就是equals / hashcode相同

addAll函数遍历原集合,插入到新set中,自然就没有重复对象了
------解决方案--------------------
HashSet不允许重复元素,具体与底层实现有关。
------解决方案--------------------
探讨
HashSet不允许重复元素,具体与底层实现有关。

------解决方案--------------------
clear方法清空arraylist中的元素;
addall把set中的元素全都拷贝进arraylist中,set的元素没有重复的,所以arraylist中此时没有重复元素了
------解决方案--------------------
各位已经说的很详细了,建议lz把 list、map、collection等的异同点好好看看
------解决方案--------------------
本质简单来说就是对hashcode和eques的重写
------解决方案--------------------
你用了 Set, 建议你看看 new HashSet(arlList)的源码
  相关解决方案