| Author |
sum of non numeric elements in an ArrayList
|
Vijay Tyagi
Ranch Hand
Joined: Feb 15, 2010
Posts: 52
|
|
why is it that the sum of all elements in the ArrayList list (code below) is 10 ?
there are non numeric elements in the arraylist
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
You are taking a "sum" of the count from zero to the size of the list.... ie 0 + 1 + 2 + 3 + 4 ==> 10.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Vijay Tyagi
Ranch Hand
Joined: Feb 15, 2010
Posts: 52
|
|
when I change it to
sum=sum+list.get(i);
I get error
TestList.java:22: operator + cannot be applied to double,java.lang.Object
sum=sum+list.get(i);
|
 |
Hunter McMillen
Ranch Hand
Joined: Mar 13, 2009
Posts: 490
|
|
The compiler is telling you that you can't add objects of different types.
"Dog" + 345678 causes an error.
Hunter
|
"If the facts don't fit the theory, get new facts" --Albert Einstein
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
|
You're trying to add together a double and an Object, which you can't do in Java.
|
Joanne
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19214
|
|
Hunter McMillen wrote:"Dog" + 345678 causes an error.
Actually that would work, if the right references are used. Remember that + is used for string concatenations. However, in this case all references are Object references, and + definitely does not work for objects.
Vijay, print out the classes of the elements. Then find out if the numeric values have a common super class (they do, and it's not Object). If so, find a method that returns something you can add together (hint: it ends with "Value"). You can use the instanceof operator and casting to give you an instance of that common super class.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Hunter McMillen
Ranch Hand
Joined: Mar 13, 2009
Posts: 490
|
|
Rob Prime wrote:
Hunter McMillen wrote:"Dog" + 345678 causes an error.
Actually that would work, if the right references are used. Remember that + is used for string concatenations. However, in this case all references are Object references, and + definitely does not work for objects.
Sorry I should have said: in this case, this will cause an error.
Hunter
|
 |
 |
|
|
subject: sum of non numeric elements in an ArrayList
|
|
|