【问题标题】:Using the same function for multiple data types对多种数据类型使用相同的函数
【发布时间】:2017-06-02 06:02:14
【问题描述】:

是否可以为不同的数据类型重用相同的函数? 因此,例如,我有一个将 Integer ArrayList 转换为 Integer 数组的函数

public static int[] arrayListToIntArray(ArrayList<Integer> list) {
    int[] out = new int[list.size()];
    int count = 0;
    for (int x : list) {
        out[count] = x;
        count++;
    }
    return out;
}

但是,如果我想用一个字节 ArrayList 做到这一点,我必须这样做

public static byte[] arrayListToByteArray(ArrayList<Byte> list) {
    byte[] out = new byte[list.size()];
    int count = 0;
    for (byte x : list) {
        out[count] = x;
        count++;
    }
    return out;
}

所以我想知道是否有比仅使用不同数据类型重复相同代码并基本上拥有相同代码的整个类更好的方法?或者我可以做点什么让它可以用于所有数据类型?

【问题讨论】:

  • 如果您想从包装器返回原始类型,则不是。如果您不介意返回Byte[]Integer[],那么您可以致电list.toArray();
  • 您正在寻找泛型。见JAVA Generics
  • 这只是我使用的一个示例,并非特定于该功能,但无论如何感谢。
  • 是的,一般来说,出于性能和 Java-y 的原因,您不想对原始类型执行此操作。最好将 Java 拆分为基于原始/数组的东西和基于对象/泛型的东西。你可以使用 Number.class 来解决这个问题,但是有一些原始版本的东西,比如流和函数是有原因的。如果您来自 C#,这是一个显着的差异。

标签: java types


【解决方案1】:

是的,你可以。它被称为Generics

public static <T> T[] arrayListToIntArray(ArrayList<T> list) {
    T[] out = (T[]) new Object[list.size()];
    int count = 0;
    for (T x : list) {
        out[count] = x;
        count++;
    }
    return out;
}

更新:

您不能实例化通用类型,因此您还可以传递另一个将作为类型的参数,请查看this

public static <T> T[] arrayListToIntArray(ArrayList<T> list, Class<T> t ) {
        T[] out = (T[]) Array.newInstance(t, list.size());
        int count = 0;
        for (T x : list) {
            out[count] = x;
            count++;
        }
        return out;
    }

【讨论】:

  • 您能解释一下为什么我的代码会出现“非法类型开始”错误吗?
  • 解决了您的问题吗?如果有,请将答案标记为解决方案,或者如果您有更多问题,请告诉我。谢谢@Nightfortress
【解决方案2】:

将方法中的类型更改为泛型,您可以这样写

public static <T> T[] arrayListToArray(ArrayList<T> list, Class<T> type) {
    @SuppressWarnings("unchecked")
    final T[] out = (T[]) Array.newInstance(type, list.size());
    int count = 0;
    for (T x : list) {
        out[count] = x;
        count++;
    }
    return out;
}

然后像这样使用它

public static void main(String[] args) {
    ArrayList<Integer> intList = new ArrayList<>();
    intList.add(13);
    intList.add(37);
    intList.add(42);
    Integer[] intArray = arrayListToArray(intList, Integer.class);

    ArrayList<Byte> byteList = new ArrayList<>();
    byteList.add((byte) 0xff);
    byteList.add((byte) 'y');
    byteList.add((byte) 17);
    Byte[] byteArray = arrayListToArray(byteList, Byte.class);

    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(byteArray));
}

输出:

[13, 37, 42]
[-1, 121, 17]

【讨论】:

    猜你喜欢
    • 2021-09-13
    • 2020-03-05
    • 1970-01-01
    • 2012-10-11
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    相关资源
    最近更新 更多