Pass T as a parameter for conditional Generic creation in Java

I am trying to conditionally create a Generic instance in Java where the type is passed as a parameter. Something like that:

private void doStuff(somethingThatDescribesWhatTShouldBeHere) {

   ArrayList<thetypeTthatwaspassedin> = new ArrayList<thetypeTthatwaspassedin>
   ... rest of logic
}

I can’t understand what life a T-parameter should look like without ArrayList<T>screaming towards me.

The idea is that Tthis is a string, then an instance is created ArrayList<String>.. if it is Foo, then an instance is created instead ArrayList<Foo>.

Please, help

+4
source share
3 answers

Well, just do doStuffgeneric:

// If you can, pass a parameter of type T :
private <T> void doStuff(T something) {

   ArrayList<T> = new ArrayList<T>();
   ... rest of logic
}
// so it can be called like that :  
YourType param = ...;
foo.doStuff(param);

// If you can't pass a parameter of type T, you'll have
// to explicitly tell the compiler which type to use :
foo.<YourType>doStuff();

Class<T>, Stijn Geukens, , .

+2

; :.

class Ideone
{

    public <T> void test (Class<T> c) {
        List<T> t = new ArrayList<T>();
    }
}
+2

Here are two common examples, one of which uses static access:

import java.util.*;

public class Utility
{
    /**
     * Returns an empty mutable non-concurrent list, likely
     * java.util.ArrayList.
     *
     * @param <T> requested type for container
     *
     * @return  mutable non-concurrent list
     **/
    public static <T> List<T> newMutableList()
    {
        return (new ArrayList<T>());
    }
}


public class Utility2<T>
{
    /**
     * Returns an empty mutable non-concurrent list, likely
     * java.util.ArrayList.
     *
     * @param <T> requested type for container
     *
     * @return  mutable non-concurrent list
     **/
    public List<T> newMutableList()
    {
        return (new ArrayList<T>());
    }
}
0
source

Source: https://habr.com/ru/post/1529594/


All Articles