I believe that the most elegant solution is to use an implementation java.util.Set, for example java.util.HashSet. For example, the following code adds all the integers in the set dto set c,
where duplicates are not added .
The code:
import java.util.HashSet;
import java.util.LinkedList;
import com.google.common.base.Joiner;
public class CollectionsTest {
public static void main(String[] args) {
HashSet<Integer> c = new HashSet<>();
c.add(0);
c.add(1);
c.add(2);
HashSet<Integer> d = new HashSet<>();
d.add(2);
d.add(3);
System.out.println("c = " + Joiner.on(", ").join(c));
System.out.println("d = " + Joiner.on(", ").join(d));
c.addAll(d);
System.out.println("c.addAll(d) = " + Joiner.on(", ").join(c));
}
}
Output:
c = 0, 1, 2
d = 2, 3
c.addAll(d) = 0, 1, 2, 3
To work HashSetcorrectly for objects of City
objection City, methods hashCode()and must be redefined equals(). Then HashSetremove duplicates when used addAll()for free!
source
share