编写Union函数以实现Java集

时间:2018-09-06 15:47:56

标签: java generics inheritance

作为练习的一部分,我必须使用链表在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();
   }
}

如果我尝试在IntSet上的a.Union(b)的{​​{1}}上调用在a, b中定义的方法,则会遇到错误,指出IntSet无法转换为Myset<Integer>。尝试强制转换会产生运行时错误。我该如何解决这个问题?

编辑:当我在{给定的IntSet上调用increment()操作(仅在子类IntSet中定义)时,会发生此错误{1}}。

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分: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();
    }
}