Hi Everyone,

I'm new here and also new in using Java.

I want to make an iterator without using the default methods hasNext, hasPrevious.

Here is what I've already done using the default methods:

import java.util.*;

public class HomeIterator{

	public static void main(String[] args) {
		int i = 0;
		ArrayList list_a = new ArrayList();
		ListIterator it = list_a.listIterator();
			while (it.hasNext()){
				Object element_list_a = it.next();
				System.out.println("Element no"+" "+i+":"+" "+element_list_a);
			while (it.hasPrevious()){
				Object element_lista_inv = it.previous();
				System.out.println("Element no"+" "+i+":"+" "+element_lista_inv);

So, I would like to do something similar to this, just without using the default hasNext, hasPrevious.

Well, I can give you a working solution.

What you can do is remove all those checks for hasNext() and hasPrevious() and enclose each while loop with a try-catch block. Because when you try to read beyond the contents of an ArrayList, you will get a "NoSuchElementFoundException". You can use this concept to break the while loop. So set the loop to loop indefinitely ("true" as condition). Now when you reach end of loop the exception will be thrown and the loop will be exited.

Same can be done for the next loop also...

Here's a pseudocode:

        read object from arrayList
        do stuff
catch (NoSuchElementFoundException)
   //Do nothing

Thanks for your quick reply.

This is not quite what I want to do. I would like to have some custom methods that have the same functionality as hasNext (and hasPrevious), but I don't know how to do it.

for ex.

public void hasNextMyMethod(){
/*do the things as hasNext method does*/

I would like to know what to write in this method (also with hasPrevious).