how to init an iterator

24,224

Solution 1

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);

Solution 2

Remove the new keyword:

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

Solution 3

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.

Share:
24,224
mkind
Author by

mkind

Updated on April 12, 2020

Comments

  • mkind
    mkind about 4 years

    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?