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

后端 未结 8 2022
逝去的感伤
逝去的感伤 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:23

    You can use the old way:

    public List magicalListGetter() {
        List list = doMagicalVooDooHere();
    
        return list;
    }
    

    or you can use Object and the parent class of everything:

    public List magicalListGetter() {
        List list = doMagicalVooDooHere();
    
        return list;
    }
    
    
    

    Note Perhaps there is a better parent class for all the objects you will put in the list. For example, Number would allow you to put Double and Integer in there.

    提交回复
    热议问题