【发布时间】:2010-12-25 04:21:18
【问题描述】:
ArrayList<String> values=new ArrayList<String>();
values.add("s");
values.add("n");
values.add("a");
values.add("s");
在这个数组中,我想删除重复的值。
【问题讨论】:
-
那你为什么不使用set呢?
ArrayList<String> values=new ArrayList<String>();
values.add("s");
values.add("n");
values.add("a");
values.add("s");
在这个数组中,我想删除重复的值。
【问题讨论】:
我认为执行唯一数组列表的一个真正巧妙的解决方案是 this one,如果它不是您想要实现的目标的太多代码。
public class UniqueOverridingList extends ArrayList {
public enum LAST_RESULT {
ADD, OVERRIDE, NOTHING;
}
private LAST_RESULT lastResult;
public boolean add(T obj) {
for (int i = 0; i < size(); i++) {
if (obj.equals(get(i))) {
set(i, obj);
lastResult = LAST_RESULT.OVERRIDE;
return true;
}
}
boolean b = super.add(obj);
if (b) {
lastResult = LAST_RESULT.ADD;
} else {
lastResult = LAST_RESULT.NOTHING;
}
return b;
}
public boolean addAll(Collection c) {
boolean result = true;
for (T t : c) {
if (!add(t)) {
result = false;
}
}
return result;
}
public LAST_RESULT getLastResult() {
return lastResult;
}
}
【讨论】:
David Hedlund 建议的课程可以缩短很多:
public class UniqueArrayList extends ArrayList {
/**
* Only add the object if there is not
* another copy of it in the list
*/
public boolean add(T obj) {
if(this.contains(obj))
return false;
return super.add(obj);
}
public boolean addAll(Collection c) {
boolean result = false;
for (T t : c) {
if (add(t)) {
result = true;
}
}
return result;
}
}
addAll 操作也被修改了。 documentation 声明:
返回:如果此列表因调用而改变,则返回 true。
我修改了方法以反映这种行为。还有一个问题。 addAll() 方法的文档还指出:
按照指定集合的迭代器返回的顺序,将指定集合中的所有元素附加到此列表的末尾。
使用此方法可能会破坏订单。此问题的可能解决方法可能是不支持addAll 方法。
【讨论】:
试试下面的代码,
ArrayList<String> values=new ArrayList<String>();
String newValue;
// repeated additions:
if (!values.contains(newValue)) {values.add(newValue);}
【讨论】:
HashSet hs = new HashSet();
hs.addAll(demoArrayList); // demoArrayList= name of arrayList from which u want to remove duplicates
demoArrayList.clear();
demoArrayList.addAll(hs);
【讨论】:
试试这个...
ArrayList<String> values=new ArrayList<String>();
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(values);
values.clear();
values.addAll(hashSet);
【讨论】: