sush uber sush uber - 21 days ago 6
Java Question

Iterator doesn't have a method to getNextElement directly without moving cursor

Why is there no method to get an element directly without iterating through it?

I have looked for an answer and found some copy-pasted answer like this:


It can be implemented on top of current Iterator interface but since its use will be rare, it doesn't make sense to include it in the interface that everyone has to implement.


What's the reason behind this?

Answer

Collection Interface extends "Iterable".So all the implementations will have to use iterator. To get an Element in map directly,we can use map.get(Key). To get an element in List we can use index. As List implements RandaomAccess Interface its easy to get an element directly using key. But in Set we cant get an element directly. The point I am trying to make is all the implementations are different but one thing is common in all the implementations we need to go through the objects inside a collection .this job is done by Iterator.

Now JAVA promotes Object Oriented programming so using iterator we can use object(Iterator instance) and call the methods hasNext() to first check if element present.It imposes a limit of iteration restriction. Then using next() we will get the next element. So hasNext() imposes a nullCheck also.

In a nutshell this promotes Object oriented concept and a flexible abstarction to be used by different implementations.

Comments