【问题标题】:Generate a variable Type of Array in the output method在输出方法中生成变量类型数组
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多