z**********r 发帖数: 86 | 1 我现在在学习Java,以前会C/C++,但是主要是用C和Matlab。
我用的是Weiss "Data Structures and Problem Solving Using Java 3rd Edition",
现在看到了第四章,关于继承。
里面有一道习题(4.23):
Write generic method max2, which accepts an array and return an array of
length two representing the two largest item in the array. The input array
should be unchanged. Then use this method on String type.
最下面是我的代码。现在我的问题是,我知道创建一个generic array是不被允许的。
StackOverflow上面有人给了一种方法:
AnyType []result=(AnyType []) new Object[2];
这种方法编译没有错的,但是运行的时候会出现[Ljava.lang.Object; cannot be cast
to [Ljava.lang.Comparable;
不知道有什么方法可以解决这个问题吗?
import java.util.ArrayList;
public class q23
{
public static void main(String []args)
{
String []arr={"write", "generic", "methods", "min", "and", "max", "
each", "of", "which", "accept", "two", "parameter"};
String []result=max2(result);
System.out.println("max2(arr)="+result[0]+" and "+result[1]);
}
public static AnyType[] void max2(AnyType[]
arr)
{
int i=0, j1=0, j2=1;
if (arr[0].compareTo(arr[1])>0)
{
j1=0;
j2=1;
}
else
{
j1=1;
j2=0;
}
for (i=2; i
{
if (arr[i].compareTo(arr[j2])>0)
{
if (arr[i].compareTo(arr[j1])>0)
{
j2=j1;
j1=i;
}
else
{
j2=i;
}
}
}
/** compiled ok but run time error: [Ljava.lang.Object; cannot be
cast to [Ljava.lang.Comparable;
ArrayList result=new ArrayList(2);
result.add(arr[j1]);
result.add(arr[j2]);
return result.toArray(null);
AnyType []result=(AnyType []) new Object[2];
result[0]=arr[j1];
result[1]=arr[j2];
return result;
*/
}
} | F****n 发帖数: 3271 | 2 Use
java.lang.reflect.Array.newInstance(AnyType.class, 2)
【在 z**********r 的大作中提到】 : 我现在在学习Java,以前会C/C++,但是主要是用C和Matlab。 : 我用的是Weiss "Data Structures and Problem Solving Using Java 3rd Edition", : 现在看到了第四章,关于继承。 : 里面有一道习题(4.23): : Write generic method max2, which accepts an array and return an array of : length two representing the two largest item in the array. The input array : should be unchanged. Then use this method on String type. : 最下面是我的代码。现在我的问题是,我知道创建一个generic array是不被允许的。 : StackOverflow上面有人给了一种方法: : AnyType []result=(AnyType []) new Object[2];
|
|