Results 1 to 4 of 4
  1. #1
    TopNFalvors is offline Member
    Join Date
    Mar 2011
    Posts
    41
    Rep Power
    0

    Default generics and iterators

    I have a generic linked list that uses an iterator to navigate through the list.

    I have this method setup in the iterator class:

    Java Code:
    public String next()
    		{
    			if (!hasNext())   //hasNext is another method in iterator
    				throw new IllegalStateException();
    			String toReturn = position.myItem;
    			position = position.next;
    			return toReturn;
    		}
    It is throwing this compile time error:
    Java Code:
    found   : T
    required: java.lang.String
    String toReturn = position.myItem;
    "myItem" is in my private class Node<T>.

    I understand that "myItem" is inside a generic class (Node<T>) so I'm guessing that's where the error is coming from.

    But how can I get the above method to return a String using a "myItem"?

    Thanks!

  2. #2
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    620
    Rep Power
    4

    Default

    Can you show a full code. Where do you use this method "next()". It's very difficult to understand what it is problem, because you posted a very short snippet.
    Skype: petrarsentev
    http://TrackStudio.com

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default

    What is myItem?

    How do you know it is a String?

  4. #4
    TopNFalvors is offline Member
    Join Date
    Mar 2011
    Posts
    41
    Rep Power
    0

    Default

    I think I figured it out...I set the method to use the generic type like this:

    Java Code:
    public T next()
    		{
    			if (!hasNext())   //hasNext is another method in iterator
    				throw new IllegalStateException();
    			T toReturn = position.myItem;
    			position = position.next;
    			return toReturn;
    		}
    Thanks!

Similar Threads

  1. Understanding Iterators
    By Domo230 in forum New To Java
    Replies: 2
    Last Post: 02-12-2011, 12:03 AM
  2. Iterators - can you assign new values to them?
    By DerekRaimann in forum New To Java
    Replies: 2
    Last Post: 12-09-2010, 07:11 PM
  3. Generics
    By sakshamkum in forum Advanced Java
    Replies: 3
    Last Post: 06-03-2010, 10:12 PM
  4. Iterator over Iterators
    By chawlakunal in forum New To Java
    Replies: 2
    Last Post: 05-22-2010, 09:16 PM
  5. Generics
    By bschmitt78 in forum Advanced Java
    Replies: 3
    Last Post: 03-16-2010, 02:21 AM

Posting Permissions

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