2

I'm trying to input a variable into an ArrayList and then add all the elements. How can i do that? The code I tried is below. Thanks.

ArrayList<String> aListNumbers = new ArrayList<String>();
int abc = 23;
aListNumbers.add("abc");
aListNumbers.add("2");
aListNumbers.add("3");

//Java ArrayList Sum All Elements

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

System.out.println("Sum of all elements of ArrayList is " + sum);
3
  • What happened when you tried it? Commented Aug 11, 2011 at 20:38
  • What are you expecting the answer to be? What are you currently getting? Commented Aug 11, 2011 at 20:40
  • guys this thing works if all the elements are passed like a string, but wont work like this, i have a different situation in my project where i want to pass a variable into the arraylist and get the total, so was trying this snippet separately. Commented Aug 11, 2011 at 20:47

2 Answers 2

7

aListNumbers.add("abc");

Here you aren't adding the contents of the variable named abc to the list. You're adding the String "abc" to the list. This will cause a NumberFormatException when the code tries to parse the character string "abc" into a number - because "abc" just isn't a number.

aListNumbers.add(abc);

That's closer to what you want, but it will still complain because the variable abc isn't a String. Since aListNumbers expects Strings (as it is an ArrayList<String>), trying to add anything else will upset the compiler.

aListNumbers.add(Integer.toString(abc));

Will work.

Sign up to request clarification or add additional context in comments.

Comments

-1

Use an ArrayList<Integer> instead of String?

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.