Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete duplicates from an ArrayList using compareTo

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.

like image 623
Adrien Varet Avatar asked May 26 '26 00:05

Adrien Varet


1 Answers

You have two options:

  • override equals() and hashcode() if you want to use a HashSet, or
  • use a TreeSet 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.

like image 108
assylias Avatar answered May 27 '26 12:05

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!