Per ogni ArrayList<Widget>
, aggiungere ogni elemento ad un Set<Widget>
(HashSet
o TreeSet
, a seconda che essi possono essere ordinati in qualche modo, o sono hashable) utilizzando addAll
. Gli insiemi non contengono duplicati per impostazione predefinita.
È possibile convertire questo Set
in uno (Array)List
se è necessario alla fine.
Nota è necessario implementare hashCode
per la classe Widget
se si decide di utilizzare un HashSet
, ma se avete un sovrascritto equals,
si dovrebbe fare in ogni caso.
Edit: Ecco un esempio:
//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;
}
}
Se si desidera utilizzare un TreeSet
, ma non si vuole implementare Comparable<T>
sulla tua classe Widget
, si può dare il set di per sé un oggetto 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());
}
});
Wow grazie @Yuushi (+1) - otterrò un'eccezione di runtime se provo ad aggiungere una vittima al set? O Java ignorerà semplicemente il dupe aggiunto (che è quello che voglio). Grazie ancora! – IAmYourFaja
Java ignorerà semplicemente il duplicato aggiunto –
@IAmYourFaja Semplicemente ignorerà il duplicato. – Yuushi