java - 仅基于对象的不同参数之一向 if 语句添加条件

标签 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;
  }
}

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

最佳答案

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

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

关于java - 仅基于对象的不同参数之一向 if 语句添加条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31799494/

相关文章:

java - 如何将规则转换为 SWRL 代码?

javascript - If 语句需要提醒用户输入的号码

c++ - 在涉及 AND 的 if 条件下避免流浪指针

arrays - 根据另一个数组上的条件构建数组

java - 理解 if 条件 - Java

java - 从集合中获取并行流

java - 如何在Java中获取二维动态数组的输入?

java - Oracle JDBCPreparedStatement 忽略尾随空格

java - 如何编辑此代码创建的按钮?

java - 检查 NaN 并在 If 中使用它