1

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;
}
2
  • 1
    Why do it like that instead of List<Integer>? Commented Oct 4, 2015 at 15:42
  • 1
    What in Object do you even want to sum? And never ever use ArrayList without type specifier. Commented Oct 4, 2015 at 15:51

2 Answers 2

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

thank you :) If I have more reputation ,my vote will change soon
@nixiehi you can always accept an answer (the "check" sign), regardless of your rep
@nixiehi Is this answer even the thing you wanted? Is the ArrayList really mixed?? I mean of course it works like that but it's not what's best if the ArrayList is just filled with Integers...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.