• Post Reply Bookmark Topic Watch Topic
  • New Topic

Navigating and referencing in a ListIterator  RSS feed

 
Dennis Noren
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to use a ListIterator to pass through a sorted ListArray. In particular, I want to confirm that there are no duplicates by comparing consecutive objects in the list. It seems that whenever next() or previous() is used, that there is an invisible pointer (pardon the expression) that moves, and I haven't been able to get this code to grab adjacent list items and to continue through all the ArrayList elements and exit the loop. I have tried various combinations of next() and previous and get, but haven't stumbled upon something that works.



This never exits the while loop, and a debugging print shows that the equals condition never evaluates to true. I think that my overloaded equals is correct, from other things that the program has done.

What is a graceful way to navigate with a ListIterator, and compare consecutive objects?
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In each iteration of that loop you are always calling both previous() and next(). This means for you are always moving backwards once, and then forwards once - thus never getting anywhere!

Additionally, I think the if statement inside the loop will never be true because the ListIterator will never have a previous item until you have called next() once!

Finally, you might want to consider using an implementation of the SortedSet interface for this, which should solve both of your requirements
 
Jacquie Barker
author
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Stuart -- selecting the right collection class for the job is like selecting the right tool: we wouldn't want to use a screwdriver to pound in a nail if a hammer is also in our toolbox. :roll eyes:

There are a handful of generic types of collections -- ordered lists (e.g., ArrayList, Vector); dictionaries/maps, which allow retrieval by key (e.g., TreeMap, Hashtable); sets, which automatically eliminate duplicates (e.g., TreeSet); and sorted sets, which do that plus order the contents.

Taking time to learn about the properties of the various types of collections in Java, then choosing the right built-in class for the job, dramatically lessens your coding efforts. For example, there's no need to explicitly write code to (a) sort, (b) eliminate duplicates from an ArrayList when a TreeSet does both automatically!

For starters, read about the following Java interfaces:

Collection
List
Map
Set
SortedSet

then investigate the various classes that implement those interfaces.

Best wishes,

Jacquie
[ July 17, 2005: Message edited by: Jacquie Barker ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!