2015-10-26 40 views
0

方法: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[] ...

我該怎麼做?

+0

'Arrays'已超載'copyOfRange'方法來處理原始類型的數組,例如'int []','double []'等等。該類中的其他方法也有相同目的的重載方法。 – rgettman

+0

你喜歡它在'Arrays'類中完成。有重載的方法接受'double []','int []'等等。 –

+0

您是否在問如何接受不同類型的參數,或者如何讓結果對象具有變量類型?第二個答案是泛型。 –

回答

0

java.util.Arrays已重載基元的方法,因爲它們不能與泛型一起使用或轉換爲對象。

這裏是方法簽名copyOf。每種方法都是截然不同的方法。

copyOf(boolean[] original, int newLength) 
copyOf(byte[] original, int newLength) 
copyOf(char[] original, int newLength) 
copyOf(double[] original, int newLength) 
copyOf(float[] original, int newLength) 
copyOf(int[] original, int newLength) 
copyOf(long[] original, int newLength) 
copyOf(short[] original, int newLength) 
copyOf(T[] original, int newLength) 

注意,其中該方法需要陣列的填充,它們每個襯墊具有不同的值:false0null取決於類型。

您也可以檢查其它的原語處理工具庫,如Guava,其具有類,如,例如:

com.google.common.primitives.Ints 
com.google.common.primitives.Longs