对于每个ArrayList<Widget>
,将每个元素添加到一个Set<Widget>
(HashSet
或TreeSet
,取决于它们是否可以以某种方式排序,或者是可散列的)利用addAll
. 默认情况下,集合不包含重复项。
如果最后需要,您可以将其转换Set
回。(Array)List
请注意,如果您决定使用 a ,您将需要hashCode
为您的类实现,但如果您有一个覆盖,则无论如何都应该这样做。Widget
HashSet
equals,
编辑:这是一个例子:
//Either the class itself needs to implement Comparable<T>, or a similar
//Comparable instance needs to be passed into a TreeSet
public class Widget implements Comparable<Widget>
{
private final String name;
private final int id;
Widget(String n, int i)
{
name = n;
id = i;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
//Something like this already exists in your class
@Override
public boolean equals(Object o)
{
if(o != null && (o instanceof Widget)) {
return ((Widget)o).getName().equals(name) &&
((Widget)o).getId() == id;
}
return false;
}
//This is required for HashSet
//Note that if you override equals, you should override this
//as well. See: http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java
@Override
public int hashCode()
{
return ((Integer)id).hashCode() + name.hashCode();
}
//This is required for TreeSet
@Override
public int compareTo(Widget w)
{
if(id < w.getId()) return -1;
else if(id > w.getId()) return 1;
return name.compareTo(w.getName());
}
@Override
public String toString()
{
return "Widget: " + name + ", id: " + id;
}
}
如果你想使用 aTreeSet
但不想Comparable<T>
在你的Widget
类上实现,你可以给集合本身一个Comparator
对象:
private Set<Widget> treeSet;
....
treeSet = new TreeSet<Widget>(new Comparator<Widget>() {
public int compare(Widget w1, Widget w2)
{
if(w1.getId() < w2.getId()) return -1;
else if(w1.getId() > w2.getId()) return 1;
return w1.getName().compareTo(w2.getName());
}
});