简体   繁体   中英

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. One or more objects will be stored in an arraylist. How can I know if the array contains one or more objects? How could I sum all first int in each object in the array?

Let array be the name of your ArrayList object. You can use:

array.size()

to check how much objects the ArrayList holds. Assuming your object looks something like this

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

You can reach a object's member by creating a instance of that 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<MyObject> list = new ArrayList<MyObject>();
int objCount = list.size();

Then if objCount > 0 you know there is at least one object in the list. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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