How to have Java method return generic list of any type?

后端 未结 8 1993
逝去的感伤
逝去的感伤 2020-11-28 07:13

I would like to write a method that would return a java.util.List of any type without the need to typecast anything:

List

        
8条回答
  •  [愿得一人]
    2020-11-28 07:29

    Let us have List objectList which we want to cast to List

    public  List list(Class c, List objectList){        
        List list = new ArrayList<>();       
        for (Object o : objectList){
            T t = c.cast(o);
            list.add(t);
        }
        return list;
    }
    
        

    提交回复
    热议问题