Java中将Element插入到Array的多个类中

我的包裹上有这些课程:


1. Class Goods with attributes (name, price, id) //Goods id is unique, but the name can be the same

2. Class Storage with attributes (Goods gArray[3])

3. Class Store with attributes (name, ArrayList<Storage>) //Store name is unique

4. Class StoreSystem with attributes (ArrayList<Store>)

我想将商品插入属于某个商店的存储中。我已经成功地将Store插入到ArrayList中,但还没有找到插入Goods的方法。


添加商店的代码如下:


public String addStore(String storeName) {

    String output = "";

    if(storeCheck(storeName)) { //storeCheck used to check whether the store name exist/not.

        output = "store already exist!";

    }

    else {

        Store s1 = new Store();

        Storage st1 = new Storage();

        s1.setStoreName(storeName);

        s1.setStorageList(null);

        st1.setGArray(null);

        listOfStore.add(s1);

        listOfStorage.add(st1);

        output = "Store added";

    }

    return output;

}


尚方宝剑之说
浏览 88回答 3
3回答

慕丝7291255

我相信就是这样,使用列表作为中间:&nbsp; &nbsp; public void addGoods(Goods g) {&nbsp; &nbsp; &nbsp; &nbsp; List<Goods> storageList = Arrays.asList(this.getGoods());&nbsp; &nbsp; &nbsp; &nbsp; storageList.add(g);&nbsp; &nbsp; &nbsp; &nbsp; this.setGoods(storageList.toArray());&nbsp; &nbsp; }像往常一样获取和设置,并且您需要控制大小。

梦里花落0921

您可以在 Storage 类中创建一个方法:要么采用数组的索引和商品作为参数,并将商品放置在数组中的该索引处(如果您有兴趣完全控制一切的去向)或者只是将商品作为参数并决定将它们放在内部的位置(如果您不关心商品转到数组中的哪个索引)那有意义吗?

12345678_0001

与现场进行POJO通话。然后在类中添加一个方法(它应该像使用一样简单,并向其传递 3 个 Goods 类型的参数)。就这样吧。你有一个and 。 StorageGoods gArray[3]StorageStorestoreArrayList.add(new Storage());StorageGoodsStorageStorage现在,在 a 中正确查找特定项Store而不为特定项分配索引Storage会有点麻烦。理想情况下,每个Storage对象都应该有一个id字段。代码看起来像这样:方法Store add:<return-type> addToStore(Goods[] goods) {&nbsp;storageArray.add(new Storage(goods));}&nbsp;&nbsp;然后Storage类将如下所示:class Storage {&nbsp;private final Goods gArray[3];&nbsp;public Storage(final Goods gArray) {&nbsp; this.gArray = gArray;&nbsp;}&nbsp;// getters}&nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java