What should I do if I want to deal with the array data[optional][3] in java on Arraylist?I looked into the method of 2D array, but I couldn't understand one more thing.
java
If you want to fill in ArrayList
an array representing one record of the SQL query results, then the following results
should look like this:
final ResultSetters=stmt.executeQuery(sql);
final List <Object[]>results=new ArrayList<>();
while(rs.next()){
finalObject[]r = newObject[3];
r[0] = rs.getString(1); // code
r[1] = rs.getString(2); // name
r[2] = rs.getBigDecimal(3); // price
results.add(r);
}
If it is not mandatory to use an array, you can also define and use a class that represents one record of the run, as described in harry0000's comment.
public classProduct{
private String code;
private String name;
private BigDecimal price;
publicProduct(final String code, final String name, final BigDecimal price) {
This.code=code;
this.name = name;
this.price=price;
}
// setter/getter omitted
}
running:
final ResultSetters=stmt.executeQuery(sql);
final List <Product>results=new ArrayList<>();
while(rs.next()){
final Product = new Product(rs.getString(1),rs.getString(2),rs.getBigDecimal(3));
results.add(r);
}
One benefit of class rather than array is the clarity of the elements to be dealt with.
For arrays, code, name, price must be determined by the subscripts of the array, or the Object
type must be downcast correctly if necessary.
(If the only use is to display it in JTable
, you may not need that kind of benefit.)
© 2024 OneMinuteCode. All rights reserved.