Using Integer [] vs. int []

I’m trying to solve the following problem: "Write an algorithm for printing all the ways of organizing eight queens on an 8x8 chessboard so that none of them share the same row, column or diagonal (i.e., others)"

I had trouble understanding why the author used Integer [] instead of the more common int [], for example, in the Integer [] and "ArrayList results" columns, which are parameters for placeQueens. My hypothesis is that this is due to generics in Java, but I'm not quite sure.

Below is a snippet of code. Link to the full code at the bottom of the page.

public static int GRID_SIZE = 8;

/* Check if (row1, column1) is a valid spot for a queen by checking if there
 * is a queen in the same column or diagonal. We don't need to check it for queens
 * in the same row because the calling placeQueen only attempts to place one queen at
 * a time. We know this row is empty. 
 */
public static boolean checkValid(Integer[] columns, int row1, int column1) {
    for (int row2 = 0; row2 < row1; row2++) {
        int column2 = columns[row2];
        /* Check if (row2, column2) invalidates (row1, column1) as a queen spot. */

        /* Check if rows have a queen in the same column */
        if (column1 == column2) { 
            return false;
        }

        /* Check diagonals: if the distance between the columns equals the distance
         * between the rows, then they're in the same diagonal.
         */
        int columnDistance = Math.abs(column2 - column1); 
        int rowDistance = row1 - row2; // row1 > row2, so no need to use absolute value
        if (columnDistance == rowDistance) {
            return false;
        }
    }
    return true;
}

public static void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> results) {
    if (row == GRID_SIZE) { // Found valid placement
        results.add(columns.clone()); 
    } else {
        for (int col = 0; col < GRID_SIZE; col++) {         
            if (checkValid(columns, row, col)) {
                columns[row] = col; // Place queen
                placeQueens(row + 1, columns, results); 
            }       
        }
    }
}

/: Cracking the Coding Interview. : https://github.com/gaylemcd/ctci/blob/master/java/Chapter%209/Question9_9/Question.java

+4
2

Java Integer , int - . Integer null. , ArrayList , Integer.

ArrayList<int[]> results = new ArrayList<int[]>();

int[] , . Integer. .

+2

, ( ):

ArrayList<Integer[]> results = new ArrayList<Integer[]>();

Integer, , , .

ArrayList<int[]> results = new ArrayList<int[]>();

. .

0

Source: https://habr.com/ru/post/1599557/


All Articles