Search code examples
javaprocessingjgraphtdigraphs

Automatically create objects based on a list's elements


I created a digraph using jgrapht library, and my vertices are Point objects I created with this code:

public static class Point {

  public int x;
  public int y;

  public  Point(int x, int y) 
  {

    this.x = x;
    this.y = y;
  }
  @Override
    public String toString() {
    return ("[x="+x+" y="+y+"]");
  }

  @Override
    public int hashCode() {
    int hash = 7;
    hash = 71 * hash + this.x;
    hash = 71 * hash + this.y;
    return hash;
  }



  @Override
    public boolean equals(Object other) 
  {
    if (this == other)
      return true;

    if (!(other instanceof Point))
      return false;

    Point otherPoint = (Point) other;
    return otherPoint.x == x && otherPoint.y == y;
  }
}

I can retrieve a vertex's successors using successorListOf() and its predecessors using predecessorListOf().

I'd like to add edges between a vertex's predecessor and its successors (in my case, there are always only one predecessor but many successors). So I'd like to do something like:

directedGraph.addEdge(Graphs.predecessorListOf(directedGraph,myPoint),Graphs.successorListOf(directedGraph,myPoint));

But these methods doesn't take as arguments a list of vertices, only one vertex at a time. What I though I should do is to automatically create a Point object for each successor and for the predecessor, but it doesn't seem appropriate since these elements are already vertices so they're also Point objects.

How can I do this ? I don't know how to create the objects based on the successors or predecessor list. Is this the right way to handle this ?


Solution

  • I don't know the jgrapht library, but can't you simply loop over the list of predecessor and successor points:

    for (Point predecessor : Graphs.predecessorListOf(directedGraph, myPoint)) {
        for (Point successor : Graphs.successorListOf(directedGraph, myPoint)) {
            directedGraph.addEdge(predecessor, successor);
        }
    }