仅基于对象的一个​​不同参数将条件添加到if语句

时间:2015-08-04 01:57:07

标签: java if-statement

我使用jgrapht库创建了一个有向图,它采用了我创建的顶点Point对象。这些对象将两个坐标和一个类型作为参数。我做了一个简单而简短的例子:

public static DirectedGraph<Point, DefaultEdge> directedGraph = new DefaultDirectedGraph<Point, DefaultEdge>(DefaultEdge.class);
public static Point firstPoint = new Point(2, 7, "A");
public static Point secondPoint = new Point(2, 8, "B");
public static Point thirdPoint = new Point(2, 9, "B");
public static Point fourthPoint = new Point(2, 4, "C");


void setup () {
  directedGraph.addVertex(firstPoint);
  directedGraph.addVertex(secondPoint);
  directedGraph.addVertex(thirdPoint);
  directedGraph.addVertex(fourthPoint);
  directedGraph.addEdge(firstPoint, secondPoint);
  directedGraph.addEdge(secondPoint, thirdPoint);
  directedGraph.addEdge(secondPoint, fourthPoint);



  int degree = directedGraph.outDegreeOf(secondPoint);
  if (degree >= 2) { 
    for (Point successor : Graphs.successorListOf (directedGraph, secondPoint)) {
      if (/*the iD is equal to B*/){
      for (Point predecessor : Graphs.predecessorListOf (directedGraph, secondPoint )) {
        directedGraph.addEdge(predecessor, successor);
      }
    }
  }
}

// --------------------------------------------------------------
public static ArrayList<Point> pointList = new ArrayList<Point>();
public static class Point {

  public int x;
  public int y;
  public String iD;
  public  Point(int x, int y, String iD) 
  {

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

  @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;
  }
}

我想在顶点的iD上的if语句中添加一个条件,而不是在我的Point对象的另外两个参数上添加条件。有没有办法做到这一点 ?

2 个答案:

答案 0 :(得分:2)

如果我理解你的问题,那么是的,这是可能的。使用public iD字段。像,

for (Point successor : Graphs.successorListOf (directedGraph, secondPoint)) {
    // if (/*the iD is equal to B*/){
    if (successor.iD.equals("B")){
        // ...
    }
}

答案 1 :(得分:1)

您已将其定义为public字段。您可以使用. Just do:

来访问它
if (successor.iD.equals("B")) {

请参阅:Oracle Tutorial on Class Members