我正在尝试构建包含单元格的行列表。已定义类行和单元格。
我想构建数组列表然后打印它。
我的代码:
import java.util.*;
public class findBfs
{
int numWarehouses;
int numCustomers = 4;
ArrayList<Integer[]> warehouses = new ArrayList<Integer[]>();
Integer[] warehouse1 = {3,6,8,2};
Integer[] warehouse2 = {6,1,2,5};
Integer[] warehouse3 = {7,8,3,9};
class Cell {
int cost;
int shipment;
public Cell(int x, int y){
x = cost;
y = shipment;
}
public int getCost(){
return cost;
}
public int getShipment(){
return shipment;
}
public void updateShipment(int newAmount){
shipment = newAmount;
}
}
class Row{
public Row(Integer[] warehouse) {
ArrayList<Cell> row = new ArrayList<Cell>();
for(int value: warehouse) {
row.add(new Cell(value, 0));
}
}
}
ArrayList<Row> tableu = new ArrayList<Row>();
public findBfs()
{
warehouses.add(warehouse1);
warehouses.add(warehouse2);
warehouses.add(warehouse3);
for(Integer[] thisWarehouse : warehouses)
{
tableu.add(new Row(thisWarehouse));
}
}
public void printTableu() {
for(Row thisRow : tableu) {
System.out.println(thisRow);
}
}
}
目前我已经打印了以下代码:
findBfs$Row@25ca623f
findBfs$Row@9f8297b
findBfs$Row@36b4f5a
发生了什么事? :(
答案 0 :(得分:2)
class Row{
ArrayList<Cell> row = new ArrayList<Cell>();
public Row(Integer[] warehouse) {
for(int value: warehouse) {
row.add(new Cell(value, 0));
}
}
}
我认为这样做并覆盖toSting()
会有所帮助
答案 1 :(得分:2)
row
ArrayList<Cell>
类型声明为构造函数的本地类型。在你的类上下文中声明它:这可能是你想要的。toString()
方法,并在Row
类中提供您希望其显示为String
的正确格式的实现。您可能需要覆盖toString()
方法并为Cell
类提供实现。list
为后缀:假设代替ArrayList<Cell>row
,将其声明为ArrayList<Cell>cellList
例如:
class Cell {
// your other code
@Override
public void String toString() {
return "shipment: " + shipment + "; cost: " + cost;
}
}
class Row{
ArrayList<Cell> cellList = new ArrayList<Cell>();
public Row(Integer[] warehouse) {
for(int value: warehouse)
cellList.add(new Cell(value, 0));
}
@Override
public void String toString() {
return cellList.toString();
}
}
修改强>
您错误地分配了类变量constructor_local_var <- class_var
:应该是class_var <-- constructor_local_var
public Cell(int x, int y){
cost = x;
shipment = y;
}
答案 2 :(得分:1)
打印对象时,首先使用String
方法将其转换为toString()
。由于您没有覆盖它,因此您将从Object
获得默认实现,正如您所看到的那样,这是非常无用的。
您应该覆盖它,就像覆盖任何其他方法一样。 E.g:
class Cell {
// snipped
@Override
public void String toString() {
return "Cell [shipment: " + shipment + "; cost: " + cost + "]";
}
}
class Row {
// snipped
@Override
public void String toString() {
// row.toString() could be simpllified to row - added for clarity.
return "Row: " + row.toString();
}
}
答案 3 :(得分:0)
您需要在warehouse
类中保存row
或Row
变量,具体取决于您要打印的内容,然后覆盖toString()
方法。< / p>
以下是Row
版本的warehouse
类的示例实现。
class Row {
private Integer[] warehouse;
public Row(Integer[] warehouse) {
this.warehouse = warehouse;
ArrayList<Cell> row = new ArrayList<Cell>();
for (int value : warehouse) {
row.add(new Cell(value, 0));
}
}
public String toString() {
return Arrays.asList(this.warehouse).toString();
}
}