[英]How to know if an arraylist contains one or more objects and how to sum one of the values of all objects in that array in Java?
let's say I have an object with one String and 2 int.假设我有一个 object,其中包含一个字符串和 2 个整数。 One or more objects will be stored in an arraylist. How can I know if the array contains one or more objects?
一个或多个对象将存储在一个 arraylist 中。我如何知道数组是否包含一个或多个对象? How could I sum all first int in each object in the array?
我怎样才能对数组中每个 object 中的所有第一个整数求和?
Let array
be the name of your ArrayList object. You can use:让
array
成为您的 ArrayList object 的名称。您可以使用:
array.size()
to check how much objects the ArrayList holds.检查 ArrayList 拥有多少对象。 Assuming your object looks something like this
假设您的 object 看起来像这样
class Foo{
String str;
int i, j;
}
You can reach a object's member by creating a instance of that object:您可以通过创建该 object 的实例来访问对象的成员:
Foo foo = new Foo(); //This creates a new instance of that object
f.i; //this would give the member i;
f.j; //this would give the member j;
To sum it all up, now you can add the created instances to the array by:总而言之,现在您可以通过以下方式将创建的实例添加到数组中:
//Assuming you have multiple instances of the object
array.add(foo);
array.add(foo2);
array.add(foo3);
//create the variable for keeping the sum.
int sum;
//Now a for loop to iterate through the elements
for(Foo f: array){
sum += f.i; //if you mean the first int by this, otherwise the j
}
If you have the arraylist declared, you can determine the number of objects currently in the list using the size() method.如果声明了 arraylist,则可以使用 size() 方法确定当前列表中的对象数。
ArrayList<MyObject> list = new ArrayList<MyObject>();
int objCount = list.size();
Then if objCount > 0
you know there is at least one object in the list.那么如果
objCount > 0
你知道列表中至少有一个 object。 As for summing the first arrays, you can iterate through the list and add the values based on property names of your objects storing the sum in a variable.至于对第一个 arrays 求和,您可以遍历列表并根据将总和存储在变量中的对象的属性名称添加值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.