views:

174

answers:

3

hi folks,

i just intent to initialize an iterator over a generic linked list like that (generic typ T seems to be erased in here since the site interpret it as tag)

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

but i got the error:

"list cannot be resolved"

what's wrong?

+10  A: 

Remove the new keyword:

Iterator<T> iter = list.iterator();
Mykola Golubyev
+1  A: 

The word followed by new operator must be a Class name. Here list.iterator() is already returning a Object. So at this point new is uncessary.

Niger
+4  A: 

To further clarify Mykola's correct answer: you're trying to create a new object of the class list. So you just want to call list.iterator() (which, somewhere inside it, is itself doing new Iterator or something like it and returning that to you).

Since you're clearly using Java 5 or above, though, the better way might be instead of doing

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

instead doing this:

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

Still better, don't write that method at all and instead use

Collections.sort(list);
Jon Bright