I'm trying to make an ArrayList of objects Edge, without any duplicates :
public class Edge implements Comparable<Edge>{
private int vertex1, vertex2;
//constructor, getter ...
@Override
public int compareTo(Edge o) {
if (vertex1 == o.getVertex1() && vertex2 == o.getVertex2()) return 0;
return 1;
}
}
I thought that using a HashSet who doesn't accept duplicates will work but I was wrong :
ArrayList<Edge> edges = new ArrayList<Edge>();
//fill list (with possible duplicates)
//delete duplicates
Set<Edge> hs = new HashSet<Edge>();
hs.addAll(edges);
edges.clear();
edges.addAll(hs);
This method works with ArrayList of String, Integer, but I don't understand why it doesn't works for this case.
Sorry for my english, I'm french.
You have two options:
equals() and hashcode() if you want to use a HashSet, orTreeSet which relies on compareTo to determine the presence of duplicates.So in your code, just replace Set<Edge> hs = new HashSet<Edge>(); with:
Set<Edge> hs = new TreeSet<Edge>();
and it will work as expected. Note that the fact that your compareTo is not consistent with equals may create other issues, so only do this if you understand what you are doing. More info in the javadoc of Comparable and TreeSet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With