• Post Reply Bookmark Topic Watch Topic
  • New Topic

Iterators & Lists -- improving code quality  RSS feed

 
D Swart
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • 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.


 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • 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.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks Rob that worked nicely.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!