Generic type as parameter in Java Method

后端 未结 3 1975
醉酒成梦
醉酒成梦 2020-12-14 06:30

Do you think it is possible to create something similar to this?

private ArrayList increaseSizeArray(ArrayList array_test, GenericClass) {
    array_test.ad         


        
3条回答
  •  猫巷女王i
    2020-12-14 07:20

    Old question but I would imagine this is the preferred way of doing it in java8+

    public  ArrayList dynamicAdd(ArrayList list, Supplier supplier) {
      list.add(supplier.get());
      return list;
    }
    

    and it could be used like this:

    AtomicInteger counter = ...;
    ArrayList list = ...;
    
    dynamicAdd(list, counter::incrementAndGet);
    

    this will add a number to the list, getting the value from AtomicInteger's incrementAndGet method

    Also possible to use constructors as method references like this: MyType::new

提交回复
热议问题