• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java class query  RSS feed

 
Aris Doxakis
Ranch Hand
Posts: 136
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good morning,
I have a simple class like below


i use it as ArrayList<lstObject>

how can i create a function in the class that sums all the Amount fileds from all the objects in the list and returns the sum of them?

in example have a function getSummary() that returns the sum of all objects in arraylist?

thanks in advance for the help.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you have to iterate the list of objects in the ArrayList to add each of the amount associated with the object.

A sample program to iterate over ArrayList...


 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi other conventions i think your code misses are -

1. Please have class name start with Upper case letter... LstObject

2. Use all upper case if its final variables... so your ID can be just id here.

3. Siera / Amount variables shall start with lower case letters.

4. instead of Obj() method to initialize the variables, use a constructor

5. If the class is used for getter setter, then use private instance variables...
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
- Please avoid double/float where exact values are required. Replace float/double fields(or localvariables if any) with BigDecimal objects.

- Make all instance fields "Private"

As John said, in your getSummary() method, declare a variable called "totalAmount" which is of the type your method returns. you'll iterate through the list in anyway you like(enchance for loop, using Iterator, using listIterator, using traditional for loop) and as you iterate through the list, for each object, get the amount and add it to the totalAmount variable and return the totalAmount.




 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Harsha Smith wrote:- Please avoid double/float where exact values are required. Replace . . . with BigDecimal . . .
Good idea. I wrote an example here.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!