简体   繁体   中英

error: method does not override or implement a method from a supertype

Building queue implementation based on linked list. Cannot run application because of the two errors:

public class Queue<Integer> implements Iterable<Integer> {
    ...
    public Iterator<Integer> iterator()  {
            return new ListIterator(first);
        }
    private class ListIterator<Integer> implements Iterator<Integer> {// error #1
            private Node<Integer> current;

            public ListIterator(Node<Integer> first) {
                current = first;
            }

            public boolean hasNext(){ return current != null;                   }
            public void remove()    { throw new UnsupportedOperationException();}

            public int next() { // error #2
                if (!hasNext()) throw new NoSuchElementException();
                int item = current.item;
                current = current.next;
                return item;
            }
        }    
     }

error #1: error: Queue.ListIterator is not abstract and does not override abstract method next() in Iterator where Integer is a type-variable: Integer extends Object declared in class Queue.ListIterator

error #2: error: next() in Queue.ListIterator cannot implement next() in Iterator return type int is not compatible with Integer where E,Integer are type-variables: E extends Object declared in interface Iterator Integer extends Object declared in class Queue.ListIterator

How to get it working?

Boxing and unboxing in Java simplify code in many places, but method return types is not one of them. The next method must return an Integer , not an int . It must match the generic type parameter exactly.

public Integer next()

Second, you've declared a generic type parameter Integer in your Queue and ListIterator classes that has nothing to do with java.lang.Integer . Remove it:

//              here
public class Queue implements Iterable<Integer> {

and

//                      here
private class ListIterator implements Iterator<Integer> {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM