• Post Reply Bookmark Topic Watch Topic
  • New Topic

Elegant Java  RSS feed

 
davoud taghawi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have an array of a class:





I am looking for an elegant way to calculate the sum of each of this variables over all agents.

Until now I use 4 functions like this:


Is there an elegant solution?

Davoud

 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since you talk about elegant Java, do yourself a favor and use descriptive variable and function names, this makes your code much more readable.
 
stanislav bashkirtsev
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Plus show other functions or describe them to make us know what they do.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12559
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
do you always need all the sums of all the variables? or are there times when you only need the 'Y' sums?

if it's an all-or-nothing, you might be able to write one method that iterates over the whole array, and keeps a sum for each variable



Then throw all those into an ArrayList (or create an ArrayList initially) and return that.

If you only need ONE sum at a time...not sure there's much else you can do.
 
Paul Clapham
Sheriff
Posts: 22713
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the new-style for loop (Java 5) looks much more elegant:

 
Sunny X Narula
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hope this looks elegant but again it all depends on what you need
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't like this approach.

Using a static variable to sum everything up means that all instances of the Agent class will be part of the sum. That also includes instances which are created in a totally different spot of the application
 
davoud taghawi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,

I took Sunny X Narula solution and modified it so that I can choose the variables to be summed up. Anyway too make this nicer?
What bothers me is that there are five lines in the main routine to get the sum. I would like a solution, where we have to write only one line of code in the main routine, to get the sum of any agent variable.

Thanks Davoud

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!