1

I want to start at the end of the list and iterate it using ListIterators previous method

public void add(E obj) {    
    ListIterator <E> iter = theList.listIterator();
    while (iter.hasNext()) {
        if (obj.compareTo(iter.next()) < 0) {
            iter.previous();
            iter.add(obj);
            return;
        }
    }
    iter.add(obj);
}

Every time I run my test class it iterators from the beginning.

2
  • Sounds like you need a doubly linked list. Do you have your linked list designed that way? If you did, you can write a custom ReverseListIterator that can traverse from the last element backwards. Commented Oct 22, 2013 at 2:07
  • It's just an ordered list with numbers 1 through 100 Commented Oct 22, 2013 at 2:10

3 Answers 3

1

to get iterator in reverse order use method list.listIterator(int index) this method will return iterator from specified position, you should put size of list means last element index. after that you can use hasPrevious() and previous() method. this will work,

 // declare arraylist
 ArrayList<...> a = new ArrayList<...>();

 // Add elements to list.

 // Generate an iterator. Start just after the last element.
 ListIterator li = a.listIterator(a.size());

 // Iterate in reverse.
  while(li.hasPrevious()) {
      System.out.println(li.previous());
  }
Sign up to request clarification or add additional context in comments.

Comments

0

ListIterator, like all Iterators, always start at the beginning. The previous method allows for less constrained movement, but it still starts at the beginning. You overall intent is unclear, so it's possible you're coming at this the wrong way, but the most straightforward way for you would be to reorder the list first and then do your iteration.

UPDATE Nevermind, Rajj has it.

Comments

0

tl;dr

In Java 21 and later:

myList.reversed().listIterator() 

SequencedCollection#reversed

In Java 21+, List is a SequencedCollection. That brings the method reversed, returning a reverse-ordered view of this collection.

for ( Person person : persons.reversed() )
{
    IO.println( person ) ;
}

If you really need an Iterator, use this:

ListIterator < Person > personsIterator = persons.reversed().listIterator() ;
…

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.