Results 1 to 14 of 14

Thread: Iterator Problem

  1. #1

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Resolved Iterator Problem

    I am iterating through a collection of customer objects in an array list.
    Code:
    public void getCustomer() //TEST, DELETE AFTERWARDS
        {
            Iterator itCount = custDB.iterator();
            Customer thisCustomer = (Customer)itCount.next();
            //Loop tthrough all customers
            while(itCount.hasNext())
            {
                thisCustomer.print(); System.out.println(); //Blank line for presentation    
                //Move to next customer
                thisCustomer = (Customer)itCount.next();
            }
        }
    This code doesn't print the last object in the arraylist but it does print the first, and the rest. What could be the problem?
    Last edited by x-ice; Feb 25th, 2007 at 07:04 PM.

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Iterator Problem

    It's simple.
    Because the last item doesn't (hasNext)
    Last edited by ComputerJy; Apr 21st, 2006 at 10:17 AM. Reason: No need to be rude
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Iterator Problem

    The answer is cryptic AND insulting. ***?

    Seriously, though, an iterator loop is written like thus:
    Code:
    Iterator it = getSomeIterator();
    while(it.hasNext()) {
      ActualType obj = (ActualType)it.next();
      // do something
    }
    Or in Java5:
    Code:
    for(ActualType obj : iterable) {
      // do something
    }
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  4. #4

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: Iterator Problem

    Solution
    Code:
    public void getCustomer() //TEST, DELETE AFTERWARDS
        {
            Iterator itCount = custDB.iterator();
            //Loop through all customers
            do
            {
                //Move to next customer
                Customer thisCustomer = (Customer)itCount.next();
                thisCustomer.print(); System.out.println(); //Blank line for presentation    
            }while(itCount.hasNext());
        }

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Iterator Problem

    What, pray tell, is wrong with my loop? Unlike yours, it won't throw a NoSuchElementException if there are no elements in the collection.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  6. #6
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Iterator Problem

    No CornedBee, his is better.
    'cause yours doesn't handle the first element
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  7. #7
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Iterator Problem

    Nonsense! You might want to confirm such claims first.
    (Ignore the generics in the code; they do not change behaviour.)
    Code:
    import java.util.*;
    
    public class IterTest
    {
    	public static void main(String[] args)
    	{
    		ArrayList<String> al = new ArrayList<String>();
    		al.add("1");
    		al.add("2");
    		al.add("3");
    
    		Iterator<String> it = al.iterator();
    		while(it.hasNext()) {
    			System.out.println(it.next());
    		}
    	}
    }
    Prints:
    1
    2
    3

    Which is the same as x-ice's method:
    Code:
    import java.util.*;
    
    public class IterTest2
    {
    	public static void main(String[] args)
    	{
    		ArrayList<String> al = new ArrayList<String>();
    		al.add("1");
    		al.add("2");
    		al.add("3");
    
    		Iterator<String> it = al.iterator();
    		do {
    			System.out.println(it.next());
    		} while(it.hasNext());
    	}
    }
    However, remove the al.add lines, and the story's different. Output of my code:
    That is, nothing, because printing all the elements of an empty list obviously yields nothing.

    x-ice's code:
    Code:
    Exception in thread "main" java.util.NoSuchElementException
            at java.util.AbstractList$Itr.next(AbstractList.java:427)
            at IterTest2.main(IterTest2.java:15)
    The semantics of Iterator state that it is only safe to call next() when a previous call to hasNext() returned true. x-ice's code calls next() before hasNext(), which is a bug.

    It should be noted that these two snippets are semantically identical, except for the scope of it:
    Code:
    Iterator it = coll.iterator();
    while(it.hasNext()) {
      it.next();
    }
    Code:
    for(Iterator it = coll.iterator(); it.hasNext(); ) {
      it.next();
    }
    An lo and behold, here's what each and every Enumeration or Iteration loop looks like in the Java API docs. The code example from java.util.Enumeration:
    Code:
    for (Enumeration e = v.elements() ; e.hasMoreElements() ;) {
         System.out.println(e.nextElement());
    }
    (Iterator and Enumeration have identical semantics. The two differences are the changed method names and the added remove() method of Iterator.)

    And here, from the presentation of the new for-loop in Java 5, are the examples of old-style loops with generics:
    Code:
    void cancelAll(Collection<TimerTask> c) {
        for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
            i.next().cancel();
    }
    Code:
        for (Iterator i = suits.iterator(); i.hasNext(); ) {
            Suit suit = (Suit) i.next();
            for (Iterator j = ranks.iterator(); j.hasNext(); )
                sortedDeck.add(new Card(suit, j.next()));
        }

    Bottom line, as arrogantly as I can put it: I'm right, you're wrong. End of discussion.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  8. #8
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Iterator Problem

    (Wow)
    I didn't really read the stuff you put in your message but you seem really pissed in the last line.
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  9. #9

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: Iterator Problem

    My code works fine, no exceptions are thrown. I have tested it.

  10. #10
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Iterator Problem

    Have you tested it with an empty customer database?
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  11. #11

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: Iterator Problem

    Quote Originally Posted by CornedBee
    Have you tested it with an empty customer database?
    I am populating an Array List (represents a customer database) earlier in the program. In order to deal with this possible exception:
    Code:
    if(custDB.Size() == 0)
    {
        //Deal with this
    }
    Also for this coursework assignment the database will never do empty (as this university module doesn't cover exception handling). We have been told to assume that.

    p.s. Take it easy, nobody said your code is wrong, better or worse.
    Last edited by x-ice; Jan 3rd, 2006 at 08:05 PM.

  12. #12
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: Iterator Problem

    p.s. Take it easy, nobody said your code is wrong, better or worse.
    I just now saw this thread. Anyone who has a little experience with Tiger would know CB is correct in all that he said. Programmers are touchy people, especially when someone who doesn't know what they're talking about jumps in and says you're wrong when it's obvious THEY are the one wrong. I would have done the same thing if faced with the situation. People like that just piss me off.

  13. #13

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: Iterator Problem

    I didn't post this topic to start an arguement. If i have offended anyone i'm sorry.

  14. #14
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: Iterator Problem

    Quote Originally Posted by x-ice
    I didn't post this topic to start an arguement. If i have offended anyone i'm sorry.
    I wasn't implying you, but lets just drop it and hopefully some people learned a few things.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width