难以将元素添加到非静态ArrayList。

huangapple go评论65阅读模式
英文:

difficulty adding to non static arraylist

问题

我正在尝试将元素添加到一个ArrayList的ArrayList中。我有一个名为"prod"的ArrayList和一个名为"shoppingBasket"的二维ArrayList。

我遇到的主要问题是,我希望将多个项目添加到购物篮中(即将多个"prod"列表添加到"shoppingBasket"列表中),但实际上它会用下一个项目替换购物篮中的第一个项目(所以购物篮中只有一个项目)。
我对Java相对新手,不太清楚如何纠正这个问题。

我还尝试创建另一个类"Item",然后从这里创建对象,然后作为ArrayList添加到ArrayList中,例如:

public class Item {
    // ... (你的Item类的定义)
}

public class Basket {
    private ArrayList<Item> shoppingBasket;
    
    public Basket() {
        shoppingBasket = new ArrayList<>();
    }
    
    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 {
    private ArrayList<ArrayList<String>> shoppingBasket;
    
    public Basket() {
        shoppingBasket = new ArrayList<>();
    }
    
    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<>();
        prod.add(Integer.toString(bar));
        prod.add(name);
        // ... (添加其他属性)
        shoppingBasket.add(prod);
        System.out.println(shoppingBasket);
    }
}

需要注意的是,这些项目是通过另一个表中的监听器从表中添加的(每个单元格是不同的变量):

selectionModel.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        // ... (获取各个属性的值)
        Basket item = new Basket();
        item.addToBasket(bar, name, type, brand, colour, con, quantity, cost, addi);
    }
});

提前感谢您的帮助 难以将元素添加到非静态ArrayList。

英文:

I am trying to add to an arraylist of arraylists. I have an arraylist called prod and 2d arraylist called shoppingBasket.

The main issue I have is that I want it to add several items to the basket (ie several prod lists to the list shoppingBasket) but instead of doing that it replaces the first item of the basket with the next (so there is only every one item in the basket).
I am fairly new to java and am not sure how to correct this.

I have also tried making another class 'item' then create objects from here then add to the arraylist as ArrayList<item>
e.g

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&lt;Item&gt; shoppingBasket;
		
	public Basket() {
		shoppingBasket = new ArrayList&lt;&gt;();
	}
	
	//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);
    }
  }
		 

When I tried this method anad printed the arraylist to test, i would just show something like [Item@23455] and would still replace the item originally there instead of adding, plus i don't really understand how to do this properly so if anyone could explain that method to me (if it is easier to use than what i have already done) it would be greatly appreciated. Although I also would prefer if I didn't have to change my code too much.

The code in question:
Function in one class that adds an item to the basket.

public class Basket {
	//arraylist for the shopping basket
	private ArrayList&lt;ArrayList&lt;String&gt;&gt; shoppingBasket;
			
	public Basket() {
		shoppingBasket = new ArrayList&lt;&gt;();
	}
			
	//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&lt;String&gt; prod = new ArrayList&lt;&gt;();
		  
		  //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. the items are being added from a table using a listener in another table (each cell is a different variable):

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);	

Thanks in advance 难以将元素添加到非静态ArrayList。

答案1

得分: 1

问题与设计/代码以及解决方案:

  1. Item不应该知道在Basket中有多少个它。在添加时应将其数量传递给篮子。因此,从Item中删除属性quantity
  2. 你需要一个Map而不是List,因为当篮子中的现有项目再次添加时,只应增加其数量。
class Basket {
    private Map<String, Integer> basket = new HashMap<String, Integer>();

    public void addToBasket(Item item, int quantity) {
        if (item != null) {
            String key = item.getName();
            basket.put(key, basket.getOrDefault(key, 0) + quantity);
        }
    }

    public void showBasket() {
        for (Entry<String, Integer> entry : basket.entrySet()) {
            System.out.println("Item = " + entry.getKey() + ", Quantity = " + entry.getValue());
        }
    }
}
  1. 每当调用valueChanged时,Basket都会被重置。将以下代码移到valueChanged之外,并将其放在类中而不是方法中。
Basket basket = new Basket();

应该这样写:

Basket basket = new Basket();
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();
        float cost = Float.parseFloat(viewAllModel.getValueAt(row, 7).toString());
        String addi = viewAllModel.getValueAt(row, 8).toString();
        basket.addToBasket(new Item(bar, name, type, brand, colour, con, cost, addi), 1);    
        //...
    }
});

一旦你将UI扩展为具有数量输入字段(文本字段/下拉菜单),你将从输入字段中获取数量,并将其传递给addToBasket,而不是传递1

英文:

Problems with your design/code & solution:

  1. An Item shouldn't know how many numbers of it is present in the Basket. Its number should be passed to the basket while adding it. So, remove the attribute, quantity from Item.
  2. You need a Map instead of a List because when an existing item in the basket is added again, only its quantity should increase.
class Basket {
	private Map&lt;String, Integer&gt; basket = new HashMap&lt;String, Integer&gt;();

	public void addToBasket(Item item, int quantity) {
		if (item != null) {
			String key = item.getName();
			basket.put(key, basket.getOrDefault(key, 0) + quantity);
		}
	}

	public void showBasket() {
		for (Entry&lt;String, Integer&gt; entry : basket.entrySet()) {
			System.out.println(&quot;Item = &quot; + entry.getKey() + &quot;, Quantity = &quot; + entry.getValue());
		}
	}
}
  1. The Basket is getting reset whenever valueChanged is invoked. Move the following code outside valueChanged and put it in the class instead of the method.
Basket item = new Basket();

It should be written like

Basket basket = new Basket();
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();
        float cost=Float.parseFloat(viewAllModel.getValueAt(row,7).toString());
        String addi= viewAllModel.getValueAt(row,8).toString();
        basket.addToBasket(new Item(bar, name, type, brand, colour, con, cost, addi), 1);    
        //...
	});

Once you will extend your UI to have an input field (textfield / dropdown) for quantity, you will get the quantity from the input field and pass the same to addToBasket instead of 1.

答案2

得分: 0

你在每次监听器中都在创建一个新的“Basket”:Basket item = new Basket();
当你每次创建一个新实例并且添加一个项目时,“新”篮子中只会有一个项目。

你需要创建一个实例(可能在你的模型中),并使用该实例来添加项目。

英文:

You are creating a new Basket every time in your listener : Basket item = new Basket();
When you create a new instance everytime and you add an item there will be only one item in the "new" basket.

You need to create one instance (probably in your model) and use that instance to add the items.

huangapple
  • 本文由 发表于 2020年5月5日 01:58:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/61598640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定