2

作为练习的一部分,我必须使用链表在 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()IntSetMyset<Integer>定的a.Union(b).

4

2 回答 2

0
class Myset<K, T> {

    public Set<T> set = new HashSet<>();

    public void setSet(Set<T> newSet) {
        this.set = newSet;
    }

    public <K extends Myset> K Union(Class<K> clazz, K val) {
        try {
            K newSet = clazz.newInstance();
            /// union code
            newSet.setSet(set);
            return newSet;
        } catch (Exception ex) {
        }
        return null;
    }
}

class IntSet extends Myset<IntSet, Integer> {
    // your functions
}

public class NewClass {
    public static void main(String args[]) {
        IntSet temp = new IntSet();
        IntSet temp2 = new IntSet();
        IntSet merge = temp.Union(IntSet.class, temp2);
    }
}
于 2018-09-06T17:29:02.210 回答
0

尝试这个:

public class MySet<T, E extends MySet> {

    public E union(MySet a) throws IllegalAccessException, InstantiationException {
        E result = (E) this.getClass().newInstance(); //The set that stores the resultant set
        //Some code to compute the union
        return result;
    }
}

和 ..

public class InSet extends MySet<Integer, InSet> {

    public InSet increment() {
        InSet temp = new InSet();
        //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[]) throws InstantiationException, IllegalAccessException {
        InSet a = new InSet();
        InSet b = new InSet();
        InSet c = a.union(b).increment();
    }
}
于 2018-09-06T18:29:35.517 回答