G
G
gleendo2017-02-13 18:38:47
Java
gleendo, 2017-02-13 18:38:47

How to implement an InputStream adapter to an Iterator?

They gave me the task to implement an InputStream adapter to an Iterator, but I can't figure out how to do it at all.
There is a blank: (You need to make a constructor and methods hasNext(), next())

public class ISToIteratorAdapter implements Iterator<Byte> {
   public ISToIteratorAdapter(InputStream is) {

   }

   @Override
   public void remove() {
       throw new UnsupportedOperationException();
   }
}

Please tell me how to implement this adapter, and explain the essence of such an implementation, because I don’t understand what it is for. Please tell me how to use it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-02-13
@evgeniy8705

Probably something like this?

public class ISToIteratorAdapter implements Iterator<Byte> {
        private final InputStream is;

        public ISToIteratorAdapter(InputStream is) {
            this.is = is;
        }

        @Override
        public boolean hasNext() {
            try {
                return is.available() > 0;
            } catch (IOException e) {
                return false;
            }
        }

        @Override
        public Byte next() {
            try {
                return Integer.valueOf(is.read()).byteValue();
            } catch (IOException e) {
                throw new NoSuchElementException();
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question