简体   繁体   English

如何将具有多个属性的对象添加到数组

[英]How to add objects with more than one attribute to an array

I'm new to java and having trouble with arrays. 我是Java新手,对数组有麻烦。 I have a Fish class and a Tank class. 我有一个鱼类班和一个坦克班。 The Fish class holds two fields, a String name and an int weight. Fish类包含两个字段,一个字符串名称和一个int权重。 In the Tank class I have to write a method that adds Fish objects to an array not an ArrayList. 在Tank类中,我必须编写一个将Fish对象添加到数组而不是ArrayList的方法。 Later on I have to write methods returning the name and the weight of the Fish Objects at specific indexes and also a method that returns an ArrayList of objects in the array. 稍后,我必须编写返回特定索引处Fish对象的名称和权重的方法,以及返回数组对象列表Array的方法。 I've already written the Fish class but am not sure how to add Objects with name and weight into an array. 我已经编写了Fish类,但是不确定如何将具有名称和权重的对象添加到数组中。 Any help would be great, Thanks. 任何帮助都会很棒,谢谢。

you just need an array like this: 您只需要一个像这样的数组:

 Fish[] fishes = new Fish[size];

then you need to create new object from Fish and set its attributes by its setters and add to the array like this: 那么您需要从Fish创建一个新对象,并通过其setter设置其属性,然后将其添加到数组中,如下所示:

Fish fish1= new Fish();
.
setting attributes
.
fishes[0]= fish1;

and so on. 等等。

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

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