Can't we do it in reverse order when we repeat from Java to ether?

Asked 2 years ago, Updated 2 years ago, 165 views

When you want to search for an array in reverse order, just turn it into a for statement,

for (int i = nodes.size() - 1; i >= 0; i--) {
    final Node each = (Node) nodes.get(i);
    ...
 }

You can do it like this.

class ListReverser<T> implements Iterable<T> {
    private ListIterator<T> listIterator;        

    public ListReverser(List<T> wrappedList) {
        this.listIterator = wrappedList.listIterator(wrappedList.size());            
    }               

    public Iterator<T> iterator() {
        return new Iterator<T>() {

            public boolean hasNext() {
                return listIterator.hasPrevious();
            }

            public T next() {
                return listIterator.previous();
            }

            public void remove() {
                listIterator.remove();
            }

        };
    }

}

In these codes, when translating into a phrase like forach,

for (final Node each : new ListReverser<Node>(nodes)) {
   //...
}

I don't know how to repeat it in reverse order. Please teach me.

java collections

2022-09-22 22:19

1 Answers

ArrayList<...> a = new ArrayList<...>();

//Add element to list 

ListIterator li = a.listIterator(a.size());

//Start navigation at the end.
while(li.hasPrevious()) {
  System.out.println(li.previous());
}

You can do it like this.


2022-09-22 22:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.