Jak sprawić, by metoda Java zwracała ogólną listę dowolnego typu?

Chciałbym napisać metodę, która zwróci java.util.List dowolnego typu bez konieczności wpisywania czegokolwiek :

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

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

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

Jak wyglądałaby sygnatura metody? Może coś takiego?):

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

    return list;
}
Z góry dzięki!
Author: Sagar Hatekar, 2013-07-24

8 answers

private Object actuallyT;

public <T> List<T> magicalListGetter(Class<T> klazz) {
    List<T> list = new ArrayList<>();
    list.add(klazz.cast(actuallyT));
    try {
        list.add(klazz.getConstructor().newInstance()); // If default constructor
    } ...
    return list;
}

Można też podać parametr typu ogólnego metody. Poprawnie wydedukowałeś, że do tworzenia rzeczy potrzebna jest poprawna instancja klasy (klazz.getConstructor().newInstance()).

 100
Author: Joop Eggen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-24 17:37:39

Nie trzeba nawet zdawać klasy:

public <T> List<T> magicalListGetter() {
    return new ArrayList<T>();
}
 16
Author: newacct,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-25 04:53:09

Inną opcją jest wykonanie następujących czynności:

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);

`

 2
Author: Aidamina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-05 08:01:47

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;
}
 2
Author: Oleg Mikhailov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-20 08:57:31

Możesz użyć starego sposobu:

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

    return list;
}

Lub możesz użyć Object i klasy nadrzędnej wszystkiego:

public List<Object> magicalListGetter() {
    List<Object> list = doMagicalVooDooHere();

    return list;
}

Uwaga być może istnieje lepsza Klasa nadrzędna dla wszystkich obiektów, które umieścisz na liście. Na przykład Number pozwoli Ci umieścić tam Double i Integer.

 1
Author: Lee Meador,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-24 17:06:48

Coś takiego

publiс <T> List<T> magicalListGetter(Class<T> clazz) {
    List list = doMagicalVooDooHere();
    return list;
}
 1
Author: Evgeniy Dorofeev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-24 17:08:09

Możesz po prostu rzucić do listy, a następnie sprawdzić, czy każdy element może być rzucony do T.

public <T> List<T> asList(final Class<T> clazz) {
    List<T> values = (List<T>) this.value;
    values.forEach(clazz::cast);
    return values;
}
 0
Author: K. Gol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-08 10:42:21

Jestem prawie pewien, że możesz całkowicie usunąć , który wygeneruje Ostrzeżenie i możesz użyć, @ tłumić Ostrzeżenia. Jeśli naprawdę chcesz, aby był ogólny, ale aby użyć dowolnego z jego elementów, będziesz musiał wykonać odlewanie typu. Na przykład zrobiłem prostą funkcję sortowania bąbelków i używa ona ogólnego typu podczas sortowania listy, która w rzeczywistości jest tablicą porównywalnych w tym przypadku. Jeśli chcesz użyć elementu, zrób coś w stylu: System.Wynocha.println ((Double)arrayOfDoubles[0] + (Double)arrayOfDoubles[1]); ponieważ wstawiłem Podwójne (S) do porównywalnych(s), co jest polimorfizmem, ponieważ wszystkie podwójne(s) dziedziczą z porównywalnych, aby umożliwić łatwe sortowanie przez zbiory.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)
 -1
Author: koZmiZm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-24 17:33:33