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

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

List<User> users = magicalListGetter(User.class);

List<Vehicle> vehicles = magicalListGetter(Vehicle.class);

List<String> strings = magicalListGetter(String.class);

What would the method signature look like? Something like this, perhaps(?):

public List<<?> ?> magicalListGetter(Class<?> clazz) {
    List<?> list = doMagicalVooDooHere();

    return list;
}

This question is related to java list generics reflection casting

The answer is


Something like this

publi? <T> List<T> magicalListGetter(Class<T> clazz) {
    List list = doMagicalVooDooHere();
    return list;
}

Let us have List<Object> objectList which we want to cast to List<T>

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

No need to even pass the class:

public <T> List<T> magicalListGetter() {
    return new ArrayList<T>();
}

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<Object> magicalListGetter() {
    List<Object> 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.


I'm pretty sure you can completely delete the <stuff> , 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)

You can simply cast to List and then check if every element can be casted to T.

public <T> List<T> asList(final Class<T> clazz) {
    List<T> values = (List<T>) this.value;
    values.forEach(clazz::cast);
    return values;
}

Another option is doing the following:

public class UserList extends List<User>{

}

public <T> T magicalListGetter(Class<T> clazz) {
    List<?> list = doMagicalVooDooHere();
    return (T)list;
}

List<User> users = magicalListGetter(UserList.class);

`


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to generics

Instantiating a generic type Are these methods thread safe? The given key was not present in the dictionary. Which key? Using Java generics for JPA findAll() query with WHERE clause Using Spring RestTemplate in generic method with generic parameter How to create a generic array? Create a List of primitive int? How to have Java method return generic list of any type? Create a new object from type parameter in generic class What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Examples related to reflection

Get properties of a class Get class name of object as string in Swift Set field value with reflection Using isKindOfClass with Swift I want to get the type of a variable at runtime Loading DLLs at runtime in C# How to have Java method return generic list of any type? Java reflection: how to get field value from an object, not knowing its class Dynamically Add C# Properties at Runtime Check if a property exists in a class

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY