About Iterators

I want to create a iterator in my program,

Node list = new Node();
Iterator it = list.iterator();
      
      while(it.hasNext())
      {
    //iterate over all the objects in the list
    Object obj = it.next();
    //do something with that object
      }
      
But when I compile the program it gives me an error (cannot resolve symbol)with  list.iterator();
should the method iterator() should be defined what it is?, if so can you give a example on what it should contain and how it will look like return types etc...
tamilthambiAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kelvin_KingCommented:
The class Node, does not have an iterator.

Perhaps you are thinking of getChildNodes(), which returns a NodeList.

So maybe something like this:

Node node = new Node();
NodeList list = node.getChildNodes();

for(int i = 0; i < list.getLength(); i ++)
{
  Node n = list.get(i);
  do_something;
}
Kelvin_KingCommented:
Here's a list of methods avaliable to you in the Node class:

http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html
CEHJCommented:
>>
Node list = new Node();
Iterator it = list.iterator();
>>

What kind of 'Node' is it? Why would there be anything to iterate if you've only just created it?
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

radarshCommented:
It's certainly not org.w3c.dom.Node as that's an interface
and you can't instantiate.

If it is something else, then that class simply doesn't implement
Iterable (JDK 1.5) or define that method directly.

________
radarsh
Kelvin_KingCommented:

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tamilthambiAuthor Commented:
I implemented my own  l-i-n-k-e-d list with "Node" as class (it could be any name).

I want to iterate through all the elements in the list using a iterator.

tNode list = new tNode();
Iterator it = list.iterator();

I have not written "class tNode implements Iterator".

should i here write my own iterator() method, if not what to do to iterate in in this case.

as otherwise iterator() gives cannot resolve symbol.
CEHJCommented:
>>should i here write my own iterator() method, if not what to do to iterate in in this case.

Yes
tamilthambiAuthor Commented:
And when I do this

Class tNode implements Iterator {

}

I get error saying
tNode is not abstract and does not override abstract method next() in java.util.Iterator

How to correct this?
CEHJCommented:
You need to provide an implementation of next() and all the other methods in the interface Iterator


public Object next() {
    return currentNode.next.data;
}
tamilthambiAuthor Commented:
In this case

tNode list = new tNode();
Iterator it = list.iterator();

give me an example of implementing my own iterator() method
CEHJCommented:
I just have, for the next() method. I'm not going to code all of it ;-)
tamilthambiAuthor Commented:
in my case  currentNode.next.data; is an integer, so it gives me an error: incompatiable types integer with object.
CEHJCommented:
It should be Object really, then it can store anything
tamilthambiAuthor Commented:
But my list is only for integers
CEHJCommented:
Use Integer and extract int from it
CEHJCommented:
You could of course return the Node itself but that's not a good solution
tamilthambiAuthor Commented:
This is my program for the list. I am able to add elements and display the list. But I am finding it difficult to build a iterator to go through the elements of the list.  I would be useful for me, if you can give any suggestions based on my program for hasNext(), next() and for iterating through the list.

import java.io.*;
import java.util.*;

 class DoubleNode  {
    DoubleNode prev;
    DoubleNode next;
    int element;
  }
   
class doubleList implements Iterator
  {
        
    DoubleNode head = null;
    DoubleNode tail = null;

 void HeadAdd(int c)
    {

      if (head == null)
        {
           head = new DoubleNode();
           head.next = null;
           head.prev = null;
     
      if (tail == null)
          {
            tail = head;
          }

        }

       else
        {

          DoubleNode tnode = new DoubleNode();
          tnode.prev = null;
          tnode.next = head;
          head.prev = tnode;
          head = tnode;
          }

        head.element = c;
    }
      
   void DisplayList()
    {
      DoubleNode tnode = new DoubleNode();
      tnode = head;
   
      while (tnode != null)
      {
             System.out.print(" " + tnode.element);
             tnode = tnode.next;
        }

        System.out.print("\n\n");
    }
       
    public boolean hasNext() {
          
    DoubleNode tnode = new DoubleNode();
     tnode = head;
   
      while (tnode != null)
      {
            System.out.print(" " + tnode.element);
             tnode = tnode.next;
        }
                
    return (tnode != null);

}

   
      public Object next() {
            
            DoubleNode tnode = new DoubleNode();
         return tnode.next.element;
    }


   public void remove() {
    throw new UnsupportedOperationException("Lister has no remove method.");
 }
   
 
 }
 
public class dlinkedlist
{

 public static void main(String args[])
 {

   doubleList objlist = new doubleList();
   objlist.HeadAdd(33);
   objlist.HeadAdd(57);

   objlist.DisplayList();
   
    doubleList dd=new doubleList();
   
      while(dd.hasNext())
      {
    System.out.println(dd.next());
      }

  }
}

CEHJCommented:
hasNext should be

public boolean hasNext() {
    return currentNode.next != null;
}
CEHJCommented:
(I've given you next())

iterator()  in your list should be:

public Iterator iterator() {
    currentNode = tail;
    return this;
}
tamilthambiAuthor Commented:
for next(), i made

public Object next() {
      
            doublenode tempnode=new doublenode ();
    return tempnode.next.element;
}

But it gives incompatiale types, I did not understand on how to convert a Object to a integer or vice versa.
as tempnode.element is a integer.
tamilthambiAuthor Commented:
I tried this but it give errors
* illegal start of type for while
and <identifier> expected

dNode tempnode=new dNode();
   
  Iterator list = tempnode.iterator();
 
while (list.hasNext()) {
      
Integer a = (Integer) list.next();
int b = a.intValue();
if ((b % 2) == 0)
System.out.println( x );

}
Kelvin_KingCommented:
if you are using java 1.5 then you have to do this:

Iterator<Integer> list = tempnode.iterator();
tamilthambiAuthor Commented:
But that still gives the same error
Kelvin_KingCommented:
It should be returning Integer value

public Integer next() {
     
          doublenode tempnode=new doublenode ();
    return tempnode.next.element;
}

Maybe you can read these links for a better understanding:

http://www-128.ibm.com/developerworks/java/library/j-forin.html
http://www-1g.cs.luc.edu/~glance/Fall01/271/Lecture/271_Lect10.htm
Kelvin_KingCommented:
this is wrong,

public Object next() {
         
          DoubleNode tnode = new DoubleNode();
         return tnode.next.element;
    }


you are creating a new tnode object, so how can it have a next ?

You should be getting the next node in your already created list of integers
Kelvin_KingCommented:
So if you have a head,

public Object next() {
         Object o;
         if( !hasNext())
              throw new NoSuchElementException(“ The List is empty.”);
          o = head.element;
           head = head.next;
           return o;
    }
Kelvin_KingCommented:
your has next method should simply be :

public boolean hasNext() {

return (head != null);

}

tamilthambiAuthor Commented:
thanks for that, but still it gives the same error saying <identifer> expected
Kelvin_KingCommented:
Ok, in that case could you post your latest code and tell me which line the error is comming from. Thanks.
tamilthambiAuthor Commented:

I am getting two errors:

incompatiale types in next() in line: o = head.element
I dont know how to resolve this,

and cannot resolve symbol iterator ()



import java.io.*;
import java.util.*;


class doubleNode
   {


    doubleNode prev;
    doubleNode next;

    int element;
   
   }



class doubleList implements Iterator
  {


    doubleNode head = null;

    doubleNode tail = null;


    void HeadAdd(int c)
    {


      if (head == null)
        {


        head = new doubleNode();
        head.next = null;
        head.prev = null;
     

        if (tail == null)
          {
            tail = head;
          }

        }

       else
        {


          doubleNode tempnode = new doubleNode();

          tempnode.prev = null;

          tempnode.next = head;

          head.prev = tempnode;

          head = tempnode;
          }


        head.element = c;


    }




   void DisplayList()
    {
      doubleNode tempnode = new doubleNode();
      tempnode = head;
     
      while (tempnode != null)
      {
             System.out.print(" " + tempnode.element);
             tempnode = tempnode.next;
        }

        System.out.print("\n\n");


    }
   
   
   
    public boolean hasNext() {
          
               return (head != null);

      }
      
      
      
      public Object next() {
            
              Object  o;
         if( !hasNext())
              throw new NoSuchElementException(" The List is empty.");
          o =  head.element;
           head = head.next;
           return o;

          }



      public void remove() {
    throw new UnsupportedOperationException("Lister has no remove method.");
       }


      
      public Iterator iterator() {
       
       doubleNode cn = new doubleNode();
    cn = tail;
    return this;
      }
      
      
      public void iteralist (){
      
      
      doubleNode tempnode= new doubleNode();
      Iterator list = tempnode.iterator();

      }
      
      
 }


public class dlinkedlist
{

 public static void main(String args[])
 {

   doubleList objlist = new doubleList();

   objlist.HeadAdd(33);
   objlist.HeadAdd(57);
   objlist.DisplayList();

  }

}

Kelvin_KingCommented:
for the first error:

>>o =  head.element;

change to o = (Object)head.element;

and second error, comment this out.

 /*
    public Iterator iterator() {
     
      doubleNode cn = new doubleNode();
    cn = tail;
    return this;
     }
 */
tamilthambiAuthor Commented:
I tried both but still the same errors appear.

If possible try to compile my file.
Manikandan ThiagarajanSenior consultantCommented:
>> doubleNode tempnode= new doubleNode();
     >>Iterator list = tempnode.iterator();

Tempnode is the doublenode object ,it dont have iterator() method

>>class doubleList implements Iterator

you create the object  doublelist and call the iterator method
tamilthambiAuthor Commented:
Thanks, that solved that problem, but still
the other exists which is  Object o = (Object) head.element;

as incomaptiable types
tamilthambiAuthor Commented:

Well, I think I am now done with all those syntax errors, but my program still has logic errors.

My iterator implemented isnt printing out the elements in the list

here is my program


import java.io.*;
import java.util.*;


class doubleNode
   {

    doubleNode prev;
    doubleNode next;

    int element;
   
   }

class doubleList implements Iterator
  {


    doubleNode head = null;

    doubleNode tail = null;


    void HeadAdd(int c)
    {


      if (head == null)
        {


        head = new doubleNode();
        head.next = null;
        head.prev = null;
     

        if (tail == null)
          {
            tail = head;
          }

        }

       else
        {


          doubleNode tempnode = new doubleNode();

          tempnode.prev = null;

          tempnode.next = head;

          head.prev = tempnode;

          head = tempnode;
          }


        head.element = c;


    }




   void DisplayList()
    {
      doubleNode tempnode = new doubleNode();
      tempnode = head;
     
      while (tempnode != null)
      {
             System.out.print(" " + tempnode.element);
             tempnode = tempnode.next;
        }

        System.out.print("\n\n");


    }
   
    doubleNode curnode = new doubleNode();

      
   
    public boolean hasNext() {
          
               return (curnode != null);

      }
      
      
      
      public Object next() {
            
        return curnode.next;

          }



      public void remove() {
          throw new UnsupportedOperationException("Lister has no remove method.");
       }


      
      public Iterator iterator() {
       
              curnode = head;
            return this;
      }
      
      
      public void iteralist (){
      
      
      doubleList tempnode= new doubleList();
      Iterator list = tempnode.iterator();

        while ( list.hasNext() ) {
        //Integer a = (Integer) list.next();

            System.out.println(list.next());

       // int b = a.intValue();
        //if ((b % 2) == 0)
             //vens.add(a);
            }


      }
      
      
 }


public class dlinkedlist
{

 public static void main(String args[])
 {


   doubleList objlist = new doubleList();

   objlist.HeadAdd(33);
   objlist.HeadAdd(57);

   objlist.DisplayList();

objlist.iteralist();

  }

}


Kelvin_KingCommented:
This works, I changed mostly the next() method, and also I changed int to Integer, because iterator.next() must return an Object. What you were doing prviously was not right. Look through the code and see if you can understand it.

import java.io.*;
import java.util.*;


class doubleNode
   {

    doubleNode prev;
    doubleNode next;

    Integer element;
   
   }

class doubleList implements Iterator
  {


    doubleNode head = null;

    doubleNode tail = null;

      doubleNode curnode = null;


    void HeadAdd(Integer c)
    {


      if (head == null)
        {


       head = new doubleNode();
       head.next = null;
       head.prev = null;
     

       if (tail == null)
         {
           tail = head;
         }

        }

       else
        {


         doubleNode tempnode = new doubleNode();

         tempnode.prev = null;

         tempnode.next = head;

         head.prev = tempnode;

         head = tempnode;
          }


        head.element = c;


    }




   void DisplayList()
    {
      doubleNode tempnode = new doubleNode();
      tempnode = head;
     
     while (tempnode != null)
     {
             System.out.print(" " + tempnode.element);
             tempnode = tempnode.next;
        }

       System.out.print("\n\n");


    }
   

     
   
    public boolean hasNext() {
         
             return (curnode != null);

     }
     
     
     
     public Object next() {
         
       Object o;
       if(hasNext()){
       o = curnode.element;
       curnode = curnode.next;
       return o;
       }
       else return null;

         }



     public void remove() {
         throw new UnsupportedOperationException("Lister has no remove method.");
      }


     
     public Iterator iterator() {
     
            curnode = head;
          return this;
     }
     
     
     public void iteralist (){
         
     doubleList tempnode= new doubleList();
     Iterator list = tempnode.iterator();

       while ( list.hasNext() ) {
        //Integer a = (Integer) list.next();

          System.out.println(list.next());

       // int b = a.intValue();
       //if ((b % 2) == 0)
             //vens.add(a);
          }


     }
     
     
 }


public class dlinkedlist
{

 public static void main(String args[])
 {


   doubleList objlist = new doubleList();

   objlist.HeadAdd(new Integer(33));
   objlist.HeadAdd(new Integer(57));

   objlist.DisplayList();

   Iterator i = objlist.iterator();

   while(i.hasNext())
     System.out.println((Integer)i.next());

  }

}
CEHJCommented:
You need to retain a reference to the current node ('currentNode' shown earlier in my examples). This needs to be an *instance* variable, not a local one
Manikandan ThiagarajanSenior consultantCommented:
tamilthambi, your program prints out 57,33

 could you please tell me,what is your exact logic and exact output ?.


CEHJCommented:
tamilthambi, can you please tell me what you accepted that answer alone after all the specific assistance i gave you?
Manikandan ThiagarajanSenior consultantCommented:
>>Thanks, that solved that problem

i gave some specific assistance, i did not get any points
Kelvin_KingCommented:
>> i gave some specific assistance, i did not get any points

That's life my friend. Sometimes, we don't always get what we want : /
Manikandan ThiagarajanSenior consultantCommented:
Kelvin_King ,Thanks for your advice in life
tamilthambiAuthor Commented:
Hello Stmani2005, sorry about that,
But I dont think one can award points to more than 1 answer in this website.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.