繁体   English   中英

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

[英]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?

假设我有一个 object,其中包含一个字符串和 2 个整数。 一个或多个对象将存储在一个 arraylist 中。我如何知道数组是否包含一个或多个对象? 我怎样才能对数组中每个 object 中的所有第一个整数求和?

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

array.size()

检查 ArrayList 拥有多少对象。 假设您的 object 看起来像这样

class Foo{
    String str;
    int i, j;
}

您可以通过创建该 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;

总而言之,现在您可以通过以下方式将创建的实例添加到数组中:

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

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

ArrayList<MyObject> list = new ArrayList<MyObject>();
int objCount = list.size();

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

暂无
暂无

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

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