作为练习的一部分,我必须使用链表在 Java 中实现集合。我在实现 Union 函数以返回泛型集时遇到了一些麻烦。
public class Myset<T> {
//Some fields and methods
public Myset<T> Union(Myset<T> a) {
Myset<T> result = new Myset<T>(); //The set that stores the resultant set
//Some code to compute the union
return result;
}
}
现在,当我尝试在特定类上使用这个集合时,我遇到了一个问题。
public class IntSet extends Myset<Integer> {
//Some methods and fields
public IntSet increment() {
IntSet temp = new IntSet();
//Makes a new IntSet temp whose elements are one obtained by adding 1 to each element of the current set
return temp;
}
public static void main(String args[]) {
IntSet a = new IntSet();
IntSet b = new IntSet();
IntSet c = a.Union(b).increment();
}
}
如果我尝试调用IntSeton a.Union(b)where a, bare instances of 中定义的方法IntSet,我会遇到一个错误,指出Myset<Integer>无法转换为IntSet. 尝试强制转换会导致运行时错误。我该如何解决这个问题?
编辑:当我increment()在IntSet给Myset<Integer>定的a.Union(b).