我正在尝试创建一个类 MyStack
来实现 java.util.collections 类。 MyStack
将覆盖集合类的一些方法,如添加(类似于推送)、删除(类似于 pop)等。我打算在与 Set< 相同的行上对类建模
或集合类的其他接口(interface),除了 MyStack
不是接口(interface)或抽象类,我们可以创建 MyStack
类型的对象。
我的语法有问题,因为我不确定我是否在朝着正确的方向前进。到目前为止我所拥有的都是这样的 - 注意 - 到目前为止还没有定义任何方法 - 我正在尝试获得在继续定义方法之前的框架。
import java.util.*;
public class MyStak implements java.util.Collection<E>{
public boolean add(E o){
return false;
}
public boolean addAll(Collection c){
return false;
}
public void clear() {
}
public boolean contains(Object o){
return false;
}
public boolean containsAll(Collection o){
return false;
}
public boolean equals(Object c){
return false;
}
public int hashcode(){
return 0;
}
public boolean isEmpty(){
return false;
}
public Iterator iterator(){
return null;
}
public boolean remove(Object o){
return false;
}
public boolean removeAll(Collection o){
return false;
}
public boolean retainAll(Collection o){
return false;
}
public int size(){
return 1;
}
public Object[] toArray(){
return null;
}
public Object[] toArray(Object[] a){
return null;
}
}
我有几个编译时错误,比如 -
+public class MyStak implements java.util.Collection<E>{
Multiple markers at this line
- The type MyStak must implement the inherited abstract method
Collection<E>.add(E)
- E cannot be resolved to a type
+public boolean add(E o){
Multiple markers at this line
- E cannot be resolved to a type
- implements
java.util.Collection<E>.add
任何代码修改、示例、对我的代码的更正、教程链接等,我们都将不胜感激。
最佳答案
确保穿上 <E>
您的类(class)规范也是如此:
public class MyStak<E> implements java.util.Collection<E>
^^^
如果你想让自己的生活更轻松,请尝试子类化 AbstractCollection
而不是实现 Collection
直接地。它为大多数方法提供了合理的默认实现,以最大限度地减少您需要编写的代码量。
java.util
Class
AbstractCollection<E>
This class provides a skeletal implementation of the
Collection
interface, to minimize the effort required to implement this interface.To implement an unmodifiable collection, the programmer needs only to extend this class and provide implementations for the
iterator
andsize
methods. (The iterator returned by theiterator
method must implementhasNext
andnext
.)To implement a modifiable collection, the programmer must additionally override this class's
add
method (which otherwise throws anUnsupportedOperationException
), and the iterator returned by theiterator
method must additionally implement itsremove
method.The programmer should generally provide a
void
(no argument) andCollection
constructor, as per the recommendation in theCollection
interface specification.
关于java - 如何创建一个实现 java.util.collections 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4301163/