0

I'm currently working with an undirected Graph and trying to get a Set with all Edges without the duplicates (So there is no need for an Edge e(start 1, end 2, weight 5) if there is already e(start 2, end 1, weight 5).

My first intention was to use Sets to solve this problem but I'm not sure how Sets do find duplicates and how to define them for Sets. There seems to be an Option to check the used Comparator but I can't find anything about changing it.

It would be brilliant if anyone could help me out with some ideas.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cipher
  • 1
  • 1
    To work with sets you need to override `hashCode` and `equals()` methods in your Edge class. Comparator would be needed if you had to order your Edges (e.g. by `start` vertex) so that `edge1 < edge2 < ... < edgeN` – Nowhere Man Jun 27 '20 at 19:24
  • Sets don't use comparators (with the exception of `TreeSet`), they use equals and hashcode. See also [Relationship between hashCode and equals method in Java](https://stackoverflow.com/questions/17027777/relationship-between-hashcode-and-equals-method-in-java) (and the linked duplicates). – Mark Rotteveel Jun 28 '20 at 11:22

1 Answers1

0

A simple solution is to make a class "Edge" and save the start, end, and weight of the edge as follows:

public class Edge {
  String start = "";
  String end = "";
  int weight = 0;

  public Edge(String start, String end, int weight) {
    this.start = start;
    this.end = end;
    this.weight = weight;
  }

  //check if the edge is the same with the intance
  public boolean isSameEdge(Edge edge) {
    if ((this.start.equals(edge.start) && this.end.equals(edge.end) && this.weight == edge.weight)) {
        return true;
    }
    return this.start.equals(edge.end) && this.end.equals(edge.start) && this.weight == edge.weight;
  }

  @Override
  public String toString() {
    return "Edge{" +
            "start='" + start + '\'' +
            ", end='" + end + '\'' +
            ", weight=" + weight +
            '}';
  }
}

And then at your main program create instances of edges and add them in an ArrayList but first check if they are already in the list.

    ArrayList<Edge> edgeArrayList = new ArrayList<>();
    Edge edge1 = new Edge("a", "b", 5);
    Edge edge2 = new Edge("b", "a", 5);
    boolean hasSame = false;
    edgeArrayList.add(edge1);
    for (Edge edge : edgeArrayList) {
        if (edge.isSameEdge(edge2)) {
            hasSame = true;
        }
    }
    if (!hasSame) {
        edgeArrayList.add(edge2);
    }
    System.out.println("List of edges: " + Arrays.toString(edgeArrayList.toArray()));

The output will be only the edge1 because edge1 and edge2 are the same.

List of edges: [Edge{start='a', end='b', weight=5}]
John Arnok
  • 594
  • 4
  • 11