nixiehi
nixiehi

Reputation: 5

java arraylist sum of objects

If the type of my ArrayList is not an Integer (They are called Objects), how can I get the sum inside of the list? newlist.get(i) will return Object and I can't sum with "sum".

ArrayList newlist = new ArrayList();
newlist.add(1);
newlist.add(2);
newlist.add(3);
newlist.add(4);

for (int i = 0; i < newlist.size(); i++) {
    sum = newlist.get(i) + sum;
}

Upvotes: 1

Views: 2067

Answers (2)

SkryptX
SkryptX

Reputation: 1001

If the ArrayList is just filled with Integers then your code would be like this:

ArrayList<Integer> newlist = new ArrayList<Integer>();
newlist.add(1);
newlist.add(2);
newlist.add(3);
newlist.add(4);

int sum = 0;

for (int i = 0; i < newlist.size(); i++) {
    sum = newlist.get(i) + sum;
}

Upvotes: 0

Mureinik
Mureinik

Reputation: 311163

You could check the runtime type and downcast the Integers:

for(int i = 0; i < newlist.size(); i++){
    Object o = newlist.get(i);
    if (o instanceof Integer) {
        sum += ((Integer) o);
    }
}

Upvotes: 2

Related Questions