How to start an iterator

I just intend to initialize the iterator over a generic linked list like this (a typical typogram T seems to be erased here since the site interprets it as a tag)

public <T> LinkedList<T> sort(LinkedList<T> list){ Iterator<T> iter = new list.iterator(); ... 

but I got an error:

"list cannot be resolved"

what's wrong?

+4
source share
3 answers

To further clarify Nikolai's correct answer: you are trying to create a new object of class list . So you just want to call list.iterator() (which, somewhere inside it, does a new Iterator or something like that and returns it to you).

Since you are explicitly using Java 5 or higher, a better way might be instead to do

 public <T> LinkedList<T> sort(LinkedList<T> list){ Iterator<T> iter = new list.iterator(); while (iter.hasNext()){ T t = iter.next(); ... } } 

instead of this:

 public <T> LinkedList<T> sort(LinkedList<T> list){ for (T t : list){ ... } } 

Better yet, do not write this method at all and use instead

 Collections.sort(list); 
+6
source

Remove the new keyword:

 Iterator<T> iter = list.iterator(); 
+11
source

The word followed by the new statement must be the name of the class. Here list.iterator () already returns an object. Thus, at the moment, a new one is not needed.

+1
source

All Articles