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