How do I find the implementation of the abstract method, hasNext()?

Viewed 1083

I'm confused about the following situation related to Java OOP and Java API/source code arrangement. Based on Oracle's Java 8 API, hasNext() is an abstract method, but I couldn't find where hasNext() is implemented. I read that private inner classes are used to implement different Iterators in each Collection class, but there is no more info about how to find the location of the implementation. Some users suggested me to add Java JRE 1.8 source code to my Eclipse IDE, but I can only see boolean hasNext(); declared as an abstract method in the Iterator interface.

As the example shown below, the iterator obj uses hasNext() directly w/o implementing it. However, I was taught you need to implement an abstract method in an interface.

My Question:
(1) How do I find the implementation of the abstract method, hasNext()? (2) A comment says I can find the code here. What's the reason to implement hasNext() in ArrayList class, but mark hasNext() as an abstract method? It is not intuitive to find the hasNext() implementation this way.

    List<String> list = new ArrayList<String>();
    list.add("item-1");
    list.add("item-2");
    list.add("item-3");

    Iterator<String> it = list.iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
4 Answers

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved.

https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

I was having the same question If ListIterator is interface which contains only abstract method which class is responsible for the implementation those methods.

arrived on the conclusion (correct me if I'm wrong)

ArrayList instance method ListIterator is returning instance of ListItr(0) ListItr(java.util.ArrayList.ListItr) is the class which is implementing the ListIterator interface with the implementation of the abstract methods. Technically ListIterator can hold instance of it's implementation class.

Related