当我实现 Queue 接口(interface)时,它要求我实现该接口(interface)中的所有抽象方法。但是,某些方法具有对象类型的输入变量。它指的是什么?是否可以将其更改为 String 类型或 java 中的任何其他原始类型?因为,例如,在这个抽象方法中:
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
public class MyQueue implements Queue {
@Override
public boolean add(Object e) {
throw new UnsupportedOperationException("Not supported yet."); /*Inserts the specified
element into this queue if it is possible to do so immediately without violating
capacity restrictions, returning true upon success and throwing an IllegalStateException
if no space is currently available.
*/
}
}
当我开始实现这个方法来制作自己的 Queue 类,其输入为 String 类型而不是 Object 类型时,它告诉我再次实现原始的抽象方法!正如您在以下片段中看到的:
@Override
public boolean add(String name) {
boolean result = true;
if (rear == maxSize - 1) {
result = false;
throw new IllegalStateException("There is No Enough Space.");
} else {
names[++rear] = name;
front = 0;
}
return result;
}
最佳答案
Queue<E>
是一个通用接口(interface)。这意味着它有一个类型参数 E
.
如果你写
class MyQueue<E> implements Queue<E> {
...
}
那么您将需要覆盖 add(E e)
,不是add(Object e)
。这可能是你应该写的。
如果你写
class MyStringQueue implements Queue<String> {
...
}
那么您将需要覆盖 add(String e)
。如果您的实现仅适用于 String
,那么您应该编写以下内容s。
如果你只是写
class MyQueue implements Queue {
...
}
那么你将被迫覆盖add(Object e)
。但是,您不应该使用原始类型 Queue
没有类型参数。
最简单的实现方式Queue
就是让你的类(class)延伸AbstractQueue<E>
因为这样大部分艰苦的工作都会为你完成。
关于java - 对象类、java API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29381089/