【发布时间】:2015-10-26 21:57:47
【问题描述】:
方法:Arrays.copyOfRange(arraySource, sourcePositionStart, sourcePositionStop) 允许我们使用特定的 startPosition 和 stopPosition 克隆 arraySource。
它适用于任何类型的数组:int[]、Integer[]、double[]、String[]、...
所以我的问题是,如何编写类似的方法,例如我想写这样的东西:
int[] newArray1 = customCloneArray(oldArray, 0, oldArray.length);
所以我尝试了这个:
public static Object[] customCloneArray(
Object[] source, int sourcePositionStart, int sourcePositionStop) {
// We give the name of class of source like Double, String
//Class theClass = (source instanceof Class? (Class)source: source.getClass());
Object[] ouput = null;
try {
if(source instanceof String[]){
ouput = (String[])Arrays.copyOfRange(source, sourcePositionStart, sourcePositionStop);
}else if(source instanceof Integer[]){
ouput = (Integer[])Arrays.copyOfRange(source, sourcePositionStart, sourcePositionStop);
}else if(source instanceof Double[]){
ouput = (Double[])Arrays.copyOfRange(source, sourcePositionStart, sourcePositionStop);
}
} catch (java.lang.IllegalArgumentException e) {
e.printStackTrace();
}
return ouput;
}
这样工作:
Integer[] newArray1 = (Integer[]) customCloneArray(oldArray, 0, oldArray.length);
String[] newArray2 = (String[]) customCloneArray(oldArray, 5, 10);
但是我想用一般的方式写这个方法,对于int[],double[] ...
我该怎么做?
【问题讨论】:
-
Arrays重载了copyOfRange方法来处理原始类型数组,例如int[]、double[]等。该类中的其他方法也具有用于相同目的的重载方法。 -
您确实喜欢在
Arrays类中完成。具有接受double[]、int[]等的重载方法。 -
您是在问如何接受不同类型的参数,或者如何获得具有变量类型的结果对象?第二个的答案是泛型。
-
@ Engineer Dollery 是的,这是我的问题,我想写这样的东西: int[] newArray = customCloneArray(OldArray, anIntegerStrat, anIntegerStop), customCloneArray 使用 Arrays.copyOfRange((OldArray, anIntegerStrat , anIntegerStop)。我知道我可以直接写:int[] newArray = Arrays.copyOfRange((OldArray, anIntegerStrat, anIntegerStop); 但我想写一个做同样事情的方法。谢谢
标签: java arrays object generics