我不明白为什么我不断收到 java.lang.ClassCastException: java.lang.Object;无法转换为 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());
}
}
包含以下
方法并扩展ProfileInterface的Profile类
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类
@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[]
但它一直给我错误
最佳答案
在我看来,您有以下选择:
保留
Set
的实现事实上,执行你的following()
无需调用的方法toArray()
,并希望没有其他人会调用toArray()
,因为如果他们这样做,它就会爆炸。去找给你作业的人,并抗议给定的作业指南无法得到合理的解决方案,因为无论是谁设计的
Set
接口(interface)显然从未实现过它,或者从未尝试调用toArray()
他们的实现方法。如果他们这样做,他们会遇到与您相同的错误。修改类的构造函数来实现
Set
接受元素的类(因此从技术上讲,您不会更改Set
的接口(interface)),因此它将按如下方式调用:
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
您尝试实现的接口(interface)是 java.util.Set
,在这种情况下它已经有 toArray( T[] )
您可以重写而不是 T[] toArray()
的方法.
关于java - 无法将对象数组转换为另一个接口(interface)的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39691627/