如何知道arraylist是否包含一个或多个对象,以及如何在Java中对该数组中所有对象的一个值求和?

如何知道arraylist是否包含一个或多个对象,以及如何在Java中对该数组中所有对象的一个值求和?,java,Java,假设我有一个对象,有一个字符串和两个int。 一个或多个对象将存储在arraylist中。 如何知道数组是否包含一个或多个对象? 如何对数组中每个对象的所有第一个int求和?如果声明了arraylist,则可以使用size()方法确定列表中当前对象的数量 ArrayList list=new ArrayList(); int objCount=list.size(); 然后,如果objCount>0您知道列表中至少有一个对象。对于第一个数组的求和,您可以遍历列表并根据将求和存储在变量中的对象的

假设我有一个对象,有一个字符串和两个int。 一个或多个对象将存储在arraylist中。 如何知道数组是否包含一个或多个对象?
如何对数组中每个对象的所有第一个int求和?

如果声明了arraylist,则可以使用size()方法确定列表中当前对象的数量

ArrayList list=new ArrayList();
int objCount=list.size();

然后,如果
objCount>0
您知道列表中至少有一个对象。对于第一个数组的求和,您可以遍历列表并根据将求和存储在变量中的对象的属性名添加值。

array
成为ArrayList对象的名称。您可以使用:

array.size()
检查ArrayList包含多少对象。 假设你的物体看起来像这样

class Foo{
    String str;
    int i, j;
}
通过创建对象的实例,可以访问该对象的成员:

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;
总而言之,现在您可以通过以下方式将创建的实例添加到阵列中:

//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
}
//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
}