我正在尝试为我在大学的任务表制作一个界面。我必须为各种数据结构实现所有这些方法,所以我想实现这个接口(interface)。
问题是,数据结构必须是通用的,例如:LinearList<T>
其中键的类型是 T。现在不同的数据结构有不同的元素 ex。一个LinearList<T>
有ListItem<T>
因为元素和树有 TreeNode<T>
.
所以我想我用<C, T>
做了一个接口(interface)其中 C = ListItem 和 T 类型 ex。整数。
现在我有一些重载方法例如:
insert(T key)
insert(ListItem<T> item)
所以用户可以添加一个键或者他可以添加例如另一个列表的头部。但是现在我遇到了一个我不明白的编译器错误:
java:15: error: name clash: insert(T,int) and insert(C,int) have the same erasure
boolean insert(T key, int pos);
我该怎么做才能按照上面解释的方式启用重载?因为在抽象类中我试过了并且成功了。
编辑: 好的,就像在讨论的评论中一样,我现在使用不同的方法名称。它似乎是其他集合用来解决问题的解决方案,并且如前所述隐藏(?)更多实现细节。非常感谢您的支持!
package interfaces;
/**
* Interface with all methods for the data-structs I have to learn for the exam
*
* <C> is the class of the Elements to be entered ex: ListItem<T>
* <T> the type of the elements stored in the data-structs
*
* @author
*/
public interface ExamPreparation<C, T> {
boolean insert(C item, int pos);
boolean insert(T key, int pos);
boolean insertAtHead(C item);
boolean insertAtHead(T key);
boolean insertAtTail(C item);
boolean insertAtTail(T key);
boolean insertSorted(C item, Comparator<T> comp);
boolean insertSorted(T key, Comparator<T> comp);
// ========== Remove Methods ==========
boolean remove(T key);
boolean removeAll(T key);
// ========== Overwrite Methods ==========
/**
* takes the first appearance of oldKey and overwrites it wit
h newKey
*
* @param newKey
* @param oldKey
* @return true if overwrited. False if oldKey is not in list
*/
boolean overwrite(T newKey, T oldKey);
/**
* takes all the oldKeys and overwrites it with the newKey
*
* @param newKey
* @param oldKey
* @return returns true if at least one oldkey was found
*/
boolean overwriteAll(T newKey, T oldKey);
/**
* overwrite at position
*
* @param newKey
* @param pos
* @return returns false if pos is not valid else true
*/
boolean overwriteAt(T newKey, int pos);
// ========== Other ==========
boolean contains(T key);
}
最佳答案
如何声明一个新接口(interface)
interface ElementType<T> {
}
然后制作可能的元素类型;像这样扩展或实现 ElememtType
:
interface ListItem<T> extends ElementType<T> {
}
interface TreeNode<T> extends ElementType<T> {
}
最后更改ExamPreparation
的声明
来自
public interface ExamPreparation<C, T>
到
public interface ExamPreparation<C extends ElementType<T>, T>
这样下面的代码编译就没有问题了;
ListItem<String> item = null;
ExamPreparation<ListItem<String>, String> examPreparation = null;
boolean isInserted;
isInserted = examPreparation.insert("12", 0);
isInserted = examPreparation.insert(item, 0);
关于Java通用接口(interface)方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48965830/