为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

尚方宝剑之说 2023-12-13 14:51:54
我的包裹上有这些课程:1. Class Goods with attributes (name, price, id) //Goods id is unique, but the name can be the same2. Class Storage with attributes (Goods gArray[3])3. Class Store with attributes (name, ArrayList<Storage>) //Store name is unique4. 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;}
查看完整描述

3 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

我相信就是这样,使用列表作为中间:


    public void addGoods(Goods g) {


        List<Goods> storageList = Arrays.asList(this.getGoods());

        storageList.add(g);

        this.setGoods(storageList.toArray());

    }

像往常一样获取和设置,并且您需要控制大小。


查看完整回答
反对 回复 2023-12-13
?
梦里花落0921

TA贡献1772条经验 获得超5个赞

您可以在 Storage 类中创建一个方法:

  • 要么采用数组的索引和商品作为参数,并将商品放置在数组中的该索引处(如果您有兴趣完全控制一切的去向)

  • 或者只是将商品作为参数并决定将它们放在内部的位置(如果您不关心商品转到数组中的哪个索引)

那有意义吗?


查看完整回答
反对 回复 2023-12-13
?
12345678_0001

TA贡献1802条经验 获得超5个赞

与现场进行POJO通话。然后在类中添加一个方法(它应该像使用一样简单,并向其传递 3 个 Goods 类型的参数)。就这样吧。你有一个and 。 StorageGoods gArray[3]StorageStorestoreArrayList.add(new Storage());StorageGoodsStorage


Storage现在,在 a 中正确查找特定项Store而不为特定项分配索引Storage会有点麻烦。理想情况下,每个Storage对象都应该有一个id字段。


代码看起来像这样:

方法Store add:


<return-type> addToStore(Goods[] goods) {

 storageArray.add(new Storage(goods));

}  

然后Storage类将如下所示:


class Storage {

 private final Goods gArray[3];


 public Storage(final Goods gArray) {

  this.gArray = gArray;

 }


 // getters

}  


查看完整回答
反对 回复 2023-12-13
  • 3 回答
  • 0 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信