954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Create an iterator (without using the default methods hasNext, hasPrevious)

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();
		
		list_a.add("bicycle");
		list_a.add("trycycle");
		list_a.add("quadrcycle");
		list_a.add("pentacycle");
		list_a.add("hexacycle");
		
		ListIterator it = list_a.listIterator();
		
			while (it.hasNext()){
				i++;
				Object element_list_a = it.next();
				System.out.println("Element no"+" "+i+":"+" "+element_list_a);
			}
		System.out.println();
		i++;
			while (it.hasPrevious()){
				i--;
				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.

sdragon
Newbie Poster
2 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

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:

try{
   while(true)
   {
        read object from arrayList
        do stuff
   }
}
catch (NoSuchElementFoundException)
{
   //Do nothing
}
stevanity
Posting Whiz in Training
293 posts since Oct 2010
Reputation Points: 43
Solved Threads: 28
 

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).

Thanks.

sdragon
Newbie Poster
2 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: