Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to init an iterator

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?

like image 427
mkind Avatar asked Dec 01 '22 07:12

mkind


2 Answers

Remove the new keyword:

Iterator<T> iter = list.iterator();
like image 92
Mykola Golubyev Avatar answered Dec 03 '22 20:12

Mykola Golubyev


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);
like image 36
Jon Bright Avatar answered Dec 03 '22 20:12

Jon Bright