Search code examples
javaloopsforeachboolean-expressionadjacency-matrix

I am trying to understand a code on adjacency matrix written in Java language ,I am not able to understand the enhanced for loop part


 // Add edges
  public void addEdge(int i, int j) {
    adjMatrix[i][j] = true;
    adjMatrix[j][i] = true;
  }

  // Remove edges
  public void removeEdge(int i, int j) {
    adjMatrix[i][j] = false;
    adjMatrix[j][i] = false;
  }

  // Print the matrix
  public String toString() {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < numVertices; i++) {
      s.append(i + ": ");
      for (boolean j : adjMatrix[i]) {
        s.append((j ? 1 : 0) + " ");
      }
      s.append("\n");
    }
    return s.toString();
  }

 

Explain the following line in the code:

 for (boolean j : adjMatrix[i]) {
        s.append((j ? 1 : 0) + " ");

the enhanced for loop using boolean operator is not clear. How to understand it and how does it work? The above code is taken by programiz.com. The above code is related to adjacency matrix.


Solution

  • enter image description here

    Take a Example

    adjMatrix = [
                [true , false , true],
                [false , false , true],
                [true , true , false]
                ]
    

    Step 1: Iterating through each row of matrix

    WHEN i = 0

    for (boolean j : [true , false , true]) {
            s.append((j ? 1 : 0) + " ");
    

    Step 2: Iterating through each boolean element of a row

    Value of j in each iteration will be:

    enter image description here

    Step 3 AND 4: Appending in S(variable) enter image description here