泛型,Casting和ArrayList(哦,我的)

时间:2016-07-12 20:17:24

标签: java generics arraylist casting

我刚刚开始使用Java进行数据结构和算法课程(我的背景主要是C ++),我在第一次任务中遇到了一些非常笨拙的事情。

我们要创建一个" set"数据结构 - 不接受重复的包。据我所知,这基本上只是一个ArrayList,在add()期间进行了一些额外的检查。

一切正常,但是当把这个集合作为数组返回时,我被迫做了一些非常笨重的事情:

class Set<T> implements SetInterface<T> {

    // Properties
    private ArrayList<T> _set = new ArrayList<T>();

    // Methods
    public Object[] toArray() {
        return this._set.toArray();
    }
}

public static void main(String[] args) {
    SetInterface<Integer> mySet = new Set<Integer>();

    // set is filled, other tests are performed...

    Object[] myArray = mySet.toArray().clone();

    for (int i = 0; i < myArray.length; i++)
        System.out.print((int)myArray[i] + " ");
}

我最初尝试返回T[]类型的数组,但抛出了ClassCastException

public T[] toArray() {
    @SuppressWarnings("unchecked")
    T[] temp = (T[])new Object[this._set.size()];
    temp = this._set.toArray(temp);
    return temp;
}

public static void main(String[] args) {
    SetInterface<Integer> mySet = new Set<Integer>();

    // set is filled, other tests are performed...

    Integer[] myArray = mySet.toArray().clone();

    for (int i = 0; i < myArray.length; i++)
        System.out.print(myArray[i] + " ");
}

现在,我的解决方案在顶级工作,但它只是......感觉不对。是否有更优雅的方式来实现这一目标?也就是说,有没有办法避免在事实之后必须在数组中强制转换每个元素?

希望这很清楚。

0 个答案:

没有答案