无法将Object数组转换为另一个接口的数组

时间:2016-09-25 20:40:52

标签: java generics casting

我无法弄清楚为什么我一直收到java.lang.ClassCastException: java.lang.Object; cannot be cast to ProfileInterface错误

以下是一直给我错误的相关代码

客户端

public static void show() {
    ProfileInterface person = pick();
    if (person == null){
        return;
    }
    System.out.println(p.getName());
    System.out.println("About: " + p.getAbout());
    System.out.println("Following:");

    //error happens at this line below
    ProfileInterface[] following = p.following(4);

    for (ProfileInterface p2 : following) {
        System.out.println(p2.getName());
    }
}

包含following方法的Profile类,并扩展了ProfileInterface

private Set<ProfileInterface> friends = new Set<ProfileInterface>();

public ProfileInterface[] following(int count){
    if(count >= friends.getCurrentSize()){

        //And points to this line as the Object Cast Error
        return (ProfileInterface[])friends.toArray();

    }else{
        return (ProfileInterface[])Arrays.copyOf(friends.toArray(), howMany);
    }
}

包含toArray方法

的Set Class
@Override
public T[] toArray() {
    T[] returnArray = (T[])new Object[size];
    System.out.println("Size of current array is " +size);
    for(int i = 0; i < size;i++){
        returnArray[i] = setArray[i];
    }

    return returnArray;
}

我正在将返回数组转换为ProfileInterface[],但它一直给我错误

1 个答案:

答案 0 :(得分:1)

在我看来,您有以下选择:

  1. 保持Set的实现不变,在不调用following()的情况下实施toArray()方法,并希望其他人不会调用toArray(),因为如果他们这样做,会爆炸。

  2. 转到给你任务的人,并抗议指定的指配无法得到合理的解决方案,因为设计Set接口的人显然从未实现过,或者从未试图调用toArray()实施方法。如果他们这样做,他们会遇到与你相同的错误。

  3. 修改实现Set的类的构造函数以接受元素的类,(从技术上讲,你不会改变Set的接口,所以它会被调用如下:

  4. Set<ProfileInterface> following = new Set<>( ProfileInterface.class );

    然后,使用以下方法从toArray()

    中创建一个数组
    public static <T> T newArray( Class<T> arrayType, int size )
    {
        assert arrayType.isArray();
        @SuppressWarnings( "unchecked" )
        T array = (T)Array.newInstance( arrayType.getComponentType(), size );
        return array;
    }
    

    (您可能希望稍微使用它以满足您的需求,例如您可能希望让它返回T[]而不是T。)

    当然,除非 您尝试实施的Set界面为java.util.Set,在这种情况下,它已经拥有{ {1}}方法,您可以覆盖而不是toArray( T[] )