Java:实现一个实例化特定类型集合的泛型方法

Hyd*_*axy 4 java generics collections

我想实现一个类似于以下内容的泛型方法:

private <T> void addToSize(ArrayList<T> list, Class<T> type, int size) {
    int currentSize = list.size();

    for(int i = currentSize; i < size; i++) {
        try {
            list.add(type.newInstance());
        } catch (InstantiationException e) {
            logger.error("", e);
        } catch (IllegalAccessException e) {
            logger.error("", e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的方法适用于这样的事情:

ArrayList<Integer> test = new ArrayList<Integer>();
addToSize(test, Integer.class, 10);
Run Code Online (Sandbox Code Playgroud)

但我也想让它为...工作

ArrayList<ArrayList<Integer>> test = new ArrayList<ArrayList<Integer>>();
addToSize(test, ArrayList.class, 10); //Is this possible?
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Boh*_*ian 6

您可以使用工厂模式:

public interface Factory<T> {
    public T create();
}

private static <T> void addToSize( ArrayList<T> list, Factory<T> factory, int size ) {
    int currentSize = list.size();

    for ( int i = currentSize; i < size; i++ ) {
        list.add( factory.create() );
    }
}
Run Code Online (Sandbox Code Playgroud)

然后为您的示例(匿名实施):

ArrayList<ArrayList<Integer>> test2 = new ArrayList<ArrayList<Integer>>();
addToSize( test2, 
    new Factory<ArrayList<Integer>>() {
       public ArrayList<Integer> create() { 
           return new ArrayList<Integer>( );
       }
    }, 10 ); // compiles
Run Code Online (Sandbox Code Playgroud)

关于这个很酷的事情是类不需要默认的构造函数,你可以将值传递给它的构造函数和/或使用构建器模式.create()方法实现的复杂性是任意的.