Iterator has .next() - is there a way to get the previous element instead of the next one?

后端 未结 10 662
离开以前
离开以前 2020-12-11 00:46

I have an Iterator that I use on a HashMap, and I save and load the iterator. is there a way to get the previous key in the HashMap with Iterator? (java.util.Iterator)

相关标签:
10条回答
  • 2020-12-11 01:25

    using iterator, No you dont have an option to get a previous key value. it has only hasNext() and next() methods.

    0 讨论(0)
  • 2020-12-11 01:26

    Make your own Iterator:

    public class EnhancedIterator<E> implements Iterator<E>{
        private List<E> list;
        private int indexSelected=-1;
        public EnhancedIterator(List<E> list){
            this.list=list;
        }
    
        @Override
        public boolean hasNext() {
            return indexSelected<list.size()-1;
        }
    
        @Override
        public E next() {
            indexSelected++;
            return current();
        }
    
        @Override
        public void remove() {
            list.remove(indexSelected);
        }
        public void remove(int i){
            list.remove(i);
            if(i<indexSelected){
                indexSelected--;
            }
        }
        public E previous(){
            indexSelected--;
            return current();
        }
        public E current(){
            return list.get(indexSelected);
        }
        public E get(int i){
            return list.get(i);
        }
    }
    
    0 讨论(0)
  • 2020-12-11 01:28

    Not directly, as others pointed out, but if you e.g. need to access one previous element you could easily save that in a separate variable.

    T previous = null;
    for (Iterator<T> i = map.keySet().iterator(); i.hasNext();) {
        T element = i.next();
    
        // Do something with "element" and "previous" (if not null)
    
        previous = element;
    }
    
    0 讨论(0)
  • 2020-12-11 01:32

    Ultimately Iterators are not fully suited for your task.

    Why not create a List from your Set (via, eg, List list = new LinkedList(set)) and iterate by using a standard indexed for-loop? That way you know the previous element is at i - 1.

    0 讨论(0)
提交回复
热议问题