简体   繁体   English

Java - 将对象数组存储为另一个对象的值并调用该值的字段

[英]Java - Store array of objects as another object's value and call that value's field

I want to store item i1 and i2 as an array in user parameter items.我想将项目 i1 和 i2 作为数组存储在用户参数项目中。 I guess this part is OK.我想这部分还可以。

class item {
    int quty;
    String name;
    double nc;

    public item(String name, int quty, double nc) {
        this.quty = quty;
        this.name = name;
        this.nc = nc;
    }

   static item i1 = new item("I1", 10, 6.04);
   static item i2 = new item("I2", 14, 8.01);
}

class user {
    String name;
    double nc;
    item[] items; // store item objects as value of user

    public user(String name, double nc, item[] items) {
        this.name = name;
        this.nc = nc;
            this.items=items;
    }

   static user u1 = new user("Tenny", 10.18, new item[]{item.i1, item.i2}  ); // user stores two items
}

Then I want to call items' names.然后我想调用项目的名称。 You can easly call item name by System.out.println(item.i1.name), but I want to call names of items that user u1 has.您可以通过 System.out.println(item.i1.name) 轻松调用项目名称,但我想调用用户 u1 拥有的项目名称。

        System.out.println("User has " + Arrays.toString((user.u1.items.name)));

Above doesn't do that.上面没有这样做。 How to do that?怎么做?

The way you are calling is incorrect as Items is an array type it requires index.您调用的方式不正确,因为 Items 是需要索引的数组类型。

user.u1.items[0].name

You can use below code to print the name of all item of user.您可以使用以下代码打印所有用户项目的名称。

 for(item i:user.u1.items) { 
     System.out.println(i.name);  
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM