泛型实现Queue接口后调用rotate方法报错:找不到符号问题解决
问题分析与解决:Queue类型调用rotate方法编译报错
问题场景
在完成课程作业时,使用测试代码验证CircularLinkedQueue的功能,添加q2.rotate(2);语句后出现编译错误:
error: cannot find symbol
提示无法找到Queue类型变量q2的rotate(int)方法。
错误原因
- 变量
q2的声明类型是Queue<String>,但提供的Queue接口仅定义了isEmpty()、enqueue(E o)、dequeue()三个方法,没有包含rotate(int)方法。 - Java的编译检查遵循"编译看声明,运行看实际"原则:引用变量只能调用其声明类型(这里是Queue接口)中存在的方法,即使实际指向的对象是
CircularLinkedQueue类型,编译器也不会识别实现类中额外定义的方法。
解决方法
方案1:修改变量声明类型(推荐,无需修改接口)
将测试代码中的变量声明改为实现类类型,这样编译器就能识别rotate方法:
// 原代码 Queue<String> q2 = new CircularLinkedQueue<String>(); // 修改后 CircularLinkedQueue<String> q2 = new CircularLinkedQueue<String>();
方案2:扩展Queue接口(仅当允许修改接口时使用)
在给定的Queue接口中添加rotate方法的定义,这样所有实现该接口的类都需要实现这个方法:
public interface Queue<E> { boolean isEmpty(); void enqueue(E o); E dequeue(); // 新增rotate方法声明 void rotate(int n); }
CircularLinkedQueue中已有的rotate实现无需修改,直接符合接口要求。
相关代码参考
CircularLinkedQueue实现代码
public class CircularLinkedQueue<E> implements Queue<E> { private static class Elem<T> { private T value; private Elem<T> next; private Elem(T value, Elem<T> next) { this.value = value; this.next = next; } } public CircularLinkedQueue () { front = rear = null; } private Elem<E> front; private Elem<E> rear; public void enqueue(E value) { if (value == null) { throw new NullPointerException(); } Elem<E> newElem = new Elem<E>(value, null ); if (rear == null) { front = rear = newElem; } else { rear.next = newElem; rear = newElem; } } public E dequeue() { E result = front.value; if (front.next == null) { front = rear = null; } else { front = front.next; } return result; } public void rotate(int n){ if (n==0){ return; } Elem<E> current= front; for (int i=0; i<n; i++){ if(current==null){ break; } current=current.next; } if (current==null){ return; } Elem<E> nthNode=current; current=current.next; current.next=front; front=nthNode.next; nthNode.next=null; } @Override public String toString() { String str = "["; Elem<E> p = front; while (p != null) { if (p != front) { str += ", "; } str += p.value; p = p.next; } str += "]"; return str; } }
测试代码(修改后版本)
public class D4Q1 { public static void main(String[] args) { CircularLinkedQueue<String> q2 = new CircularLinkedQueue<String>(); q2.enqueue("A"); q2.enqueue("B"); q2.enqueue("C"); q2.enqueue("D"); q2.enqueue("E"); q2.enqueue("F"); System.out.println(q2); q2.dequeue(); q2.dequeue(); System.out.println(q2); q2.rotate(2); System.out.println(q2); } }
原Queue接口代码
public interface Queue<E> { boolean isEmpty(); void enqueue(E o); E dequeue(); }
内容的提问来源于stack exchange,提问作者Kath
相关产品推荐
相关产品推荐

