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

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

    I'm pretty sure you can completely delete the , which will generate a warning and you can use an, @ suppress warnings. If you really want it to be generic, but to use any of its elements you will have to do type casting. For instance, I made a simple bubble sort function and it uses a generic type when sorting the list, which is actually an array of Comparable in this case. If you wish to use an item, do something like: System.out.println((Double)arrayOfDoubles[0] + (Double)arrayOfDoubles[1]); because I stuffed Double(s) into Comparable(s) which is polymorphism since all Double(s) inherit from Comparable to allow easy sorting through Collections.sort()

            //INDENT TO DISPLAY CODE ON STACK-OVERFLOW
    @SuppressWarnings("unchecked")
    public static void simpleBubbleSort_ascending(@SuppressWarnings("rawtypes") Comparable[] arrayOfDoubles)
    {
    //VARS
        //looping
        int end      =      arrayOfDoubles.length - 1;//the last index in our loops
        int iterationsMax = arrayOfDoubles.length - 1;
    
        //swapping
        @SuppressWarnings("rawtypes")
        Comparable tempSwap = 0.0;//a temporary double used in the swap process
        int elementP1 = 1;//element + 1,   an index for comparing and swapping
    
    
    //CODE
        //do up to 'iterationsMax' many iterations
        for (int iteration = 0; iteration < iterationsMax; iteration++)
        {
            //go through each element and compare it to the next element
            for (int element = 0; element < end; element++)
            {
                elementP1 = element + 1;
    
                //if the elements need to be swapped, swap them
                if (arrayOfDoubles[element].compareTo(arrayOfDoubles[elementP1])==1)
                {
                    //swap
                    tempSwap = arrayOfDoubles[element];
                    arrayOfDoubles[element] = arrayOfDoubles[elementP1];
                    arrayOfDoubles[elementP1] = tempSwap;
                }
            }
        }
    }//END public static void simpleBubbleSort_ascending(double[] arrayOfDoubles)
    

提交回复
热议问题