• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Iterators & Lists -- improving code quality

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a question about how to improve my code style .

Consider the following snippet, which calculates a score for each person in an ArrayList of people:

How do I make the code below better? Specifically:

- Is there a way to get the current element in the ArrayList without moving to the next element the way iter.next() does?
- If I want to write a value back to the list that is being iterated over, how do I do this?

Thanks.


 
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you can use for:each loop to iterate.
and to add a value you can use add(index, element);

I dont know if I am right.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

D Swart wrote:- Is there a way to get the current element in the ArrayList without moving to the next element the way iter.next() does?


The only other way is to use indexes directly. An iterator is better since it will be better if you decide to switch to a LinkedList.

- If I want to write a value back to the list that is being iterated over, how do I do this?


If you are using an Iterator, switch to using a ListIterator instead (use the listIterator() method). That one has methods for adding and replacing elements.
If you are using an index you can just use the List's add methods.
 
D Swart
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Rob that worked nicely.
reply
    Bookmark Topic Watch Topic
  • New Topic