【发布时间】:2020-05-04 17:58:03
【问题描述】:
我正在尝试添加到数组列表的数组列表中。我有一个名为 prod 的数组列表和一个名为 shoppingBasket 的二维数组列表。
我遇到的主要问题是我希望它在购物篮中添加几件商品(即在购物篮列表中添加几个产品列表),但它没有这样做,而是将购物篮的第一项替换为下一项(所以有仅购物篮中的每一项)。 我对java相当陌生,不知道如何纠正这个问题。
我也尝试过创建另一个类“项目”,然后从这里创建对象,然后作为 ArrayList 添加到数组列表中 例如
public class Item {
private int bar;
private String name;
private String type;
private String brand;
private String colour;
private String con;
private int quantity;
private float cost;
private String addi;
public Item (int bar, String name, String type, String brand, String colour, String con, int quantity,float cost, String addi) {
this.bar = bar;
this.name = name;
this.type = type;
this.brand = brand;
this.colour = colour;
this.con = con;
this.quantity = quantity;
this.cost = cost;
this.addi = addi;
}
public class Basket {
//arraylist for the shopping basket
private ArrayList<Item> shoppingBasket;
public Basket() {
shoppingBasket = new ArrayList<>();
}
//function adding items to the basket
public void addToBasket(int bar, String name, String type, String brand, String colour, String con, int quantity, float cost, String addi) {
Item items = new Item (bar, name, type, brand, colour, con, quantity, cost, addi);
shoppingBasket.add(items);
}
}
当我尝试此方法并打印 arraylist 进行测试时,我只会显示 [Item@23455] 之类的内容,并且仍然会替换原来的项目而不是添加,而且我真的不明白如何正确执行此操作因此,如果有人可以向我解释该方法(如果它比我已经做过的更容易使用),那将不胜感激。尽管我也希望不必过多地更改代码。
有问题的代码: 一个类中的函数,用于将项目添加到购物篮。
public class Basket {
//arraylist for the shopping basket
private ArrayList<ArrayList<String>> shoppingBasket;
public Basket() {
shoppingBasket = new ArrayList<>();
}
//function adding items to the basket
public void addToBasket(int bar, String name, String type, String brand, String colour, String con, int quantity, float cost, String addi) {
ArrayList<String> prod = new ArrayList<>();
//adding one item to the basket shop.add(bar); shop.add(name);
prod.add(Integer.toString(bar));
prod.add(name);
prod.add(type);
prod.add(brand);
prod.add(colour);
prod.add(con);
prod.add(Integer.toString(quantity));
prod.add(Float.toString(cost));
prod.add(addi);
shoppingBasket.add(prod);
System.out.println(shoppingBasket);
}
n.b.正在使用另一个表中的侦听器从表中添加项目(每个单元格都是不同的变量):
selectionModel.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int row = tableViewAll.getSelectedRow();
viewAllModel=(DefaultTableModel) tableViewAll.getModel();
int bar=Integer.parseInt(viewAllModel.getValueAt(row,0).toString());
String name = viewAllModel.getValueAt(row,1).toString();
String type = viewAllModel.getValueAt(row,2).toString();
String brand = viewAllModel.getValueAt(row,3).toString();
String colour= viewAllModel.getValueAt(row,4).toString();
String con = viewAllModel.getValueAt(row,5).toString();
int quantity=1;
float cost=Float.parseFloat(viewAllModel.getValueAt(row,7).toString());
String addi= viewAllModel.getValueAt(row,8).toString();
Basket item = new Basket();
item.addToBasket(bar, name, type, brand, colour, con, quantity, cost, addi);
提前致谢:)
【问题讨论】: