ArrayIndexOutOfBoundsException 错误,但我认为代码没问题

ArrayIndexOutOfBoundsException error but I think the code is okay

所以我有一个函数可以从我的数据库中填充 JTable。

我这里有

public static TableModel resultSetToTableModel(ResultSet rs) {
try {
    ResultSetMetaData metaData = rs.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    Vector<String> columnNames = new Vector<String>();

    // Get the column names
    for (int column = 0; column < numberOfColumns; column++) {
    columnNames.addElement(metaData.getColumnLabel(column + 1));
    }

    // Get all rows.
    Vector<Vector<Object>> rows = new Vector<Vector<Object>>();

    while (rs.next()) {
    Vector<Object> newRow = new Vector<Object>();

    for (int i = 1; i <= numberOfColumns; i++) {

                if(isObjectInteger(rs.getObject(i)) && i>1) //checks if the value is Integer else not and is past the first column
                {
                    System.out.println(i+"="+rs.getObject(i));
                    String label = columnNames.get(i); //THE ERROR IS ON THIS PART
                    newRow.addElement(getValue((Integer) rs.getObject(i),label)); //gets the value of specific foreign key id from another table
                }
                else 
                {
                    System.out.println(i+"="+rs.getObject(i));
                    newRow.addElement(rs.getObject(i));
                } //inside row (new Rows)
    }

    rows.addElement(newRow); //outside row
    }
    return new DefaultTableModel(rows, columnNames)
        {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
} catch (Exception e) {
    e.printStackTrace();

    return null;
}
}

我的数据库中共有 8 列 System.out.println 的输出是:

得到的在其他里面:

1=1
2=test
3=A.
4=test
5=test
6=test

得到的那个在 if

里面
7=1
8=23

如您所见,输出是正确的,但它总是在 String label = columnNames.get(i);

上抛出 Array index out of range: 8 错误

虽然 ResultSet.getObject() 需要基于一的参数,但 columnNames 是一个向量,其索引基于零。

因此它的有效值为 0..7 而不是 1..8。换句话说,if 语句的第一部分应该是:

System.out.println(i + "=" + rs.getObject(i));
String label = columnNames.get(i-1); // NOT "i".