Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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());
    }
like image 932
LED Fantom Avatar asked Jan 16 '26 22:01

LED Fantom


1 Answers

You can see in your code, that List is an ArrayList. The method in ArrayList called iterator() will return an implementation of Iterator. This implementation of Iterator will have the method hasNext() implemented.

It's great to be curious, and as the comment said, you can click into the code in an IDE (or if that doesn't work for you, set a break point in a debugger and step in). Reading the Java code is a great way to de-mystify it.

Of course, you can generally can expect the Java people to know what they are doing, and trust the implementations you get back to be sensible, and fit for general use. The caveat here is that you should also read the documentation. eg. from https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

like image 164
Brian Avatar answered Jan 19 '26 14:01

Brian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!