重构方法使用泛型

Ced*_*Sun 2 java generics

起初我写道:

private ArrayList<Integer> getDataList() {
    ArrayList<Integer> dataList = new ArrayList<>(LEN);
    for (int i = 0; i < LEN; i++)
        dataList.add(i);
    Collections.shuffle(dataList);
    return dataList;
}
Run Code Online (Sandbox Code Playgroud)

后来我决定使用泛型:

private <E> ArrayList<E> getDataList() {
    ArrayList<E> dataList = new ArrayList<>(LEN);
    for (int i = 0; i < LEN; i++)
        dataList.add(/* a procedure that generates E instance from index i*/);
    Collections.shuffle(dataList);
    return dataList;
}
Run Code Online (Sandbox Code Playgroud)

接口中的静态方法不能覆盖,因此无法在E上调用静态方法来生成实例.

如何重构这个使用泛型?谢谢.

And*_*ner 7

您需要提供将创建作为方法参数的内容:

private <E> ArrayList<E> getDataList(IntFunction<? extends E> fn) {
Run Code Online (Sandbox Code Playgroud)

然后:

dataList.add(fn.apply(i));
Run Code Online (Sandbox Code Playgroud)

并调用如下:

List<Integer> integerList = getDataList(Integer::valueOf); // Same output as non-generic code.
List<String> stringList = getDataList(i -> "Item " + i);
Run Code Online (Sandbox Code Playgroud)