13

Normally if we want to initialize a generic non-primitive ArrayList we do this

ArrayList<?> arrayList = new ArrayList<MyClass.class>();

But I want to do something similar to this no matter which class object I pass, i.e

private void getModel(Class responseType){

   //Something similar, because this does not work..                                                       
   ArrayList<?> arrayList = new ArrayList<responseType>();
}

Any Help would be greatly appreciated.

18
  • 2
    how about this private void getModel(T extends Object){ ArrayList<T> arrayList = new ArrayList<T>(); } Commented Mar 29, 2013 at 5:29
  • what you want to do ?? Commented Mar 29, 2013 at 5:29
  • 1
    Generics is for compile time type-safety. ArrayList<MyType> is type-erased to ArrayList after compilation. It's not possible to invoke new ArrayList<MyType>() at runtime, you have to call new ArrayList(). Commented Mar 29, 2013 at 5:31
  • @Vinoth please elaborate This doesn't work as well ArrayList<? extends responseType> arrayList = (ArrayList<? extends responseType>) new ArrayList<Class>(); Commented Mar 29, 2013 at 5:36
  • 1
    I already wrote that you cannot initialize a list of some type that you don't you about. Your only option is to use the non generic version ArrayList. Commented Mar 29, 2013 at 6:17

3 Answers 3

17

Try something like this

     private <T> void setModel(Class<T> type) {
      ArrayList<T> arrayList = new ArrayList<T>();
   }

If you want to get the list back then

private <T> ArrayList<T> getModel(Class<T> type) {
      ArrayList<T> arrayList = new ArrayList<T>();
      return arrayList;
   }

EDIT

A FULL EXAMPLE SHOWING HOW TO USE GENERIC TYPE FOR ARRAYLIST

Tester class with main method and the generic Method

public class Tester {

    private <T> ArrayList<T> getModels(Class<T> type) {
        ArrayList<T> arrayList = new ArrayList<T>();
        return arrayList;
    }


    public static void main(String[] args) {
        Data data = new Data(12, "test_12");
        Magic magic = new Magic(123, "test_123");

        Tester t = new Tester();

        ArrayList<Data> datas = (ArrayList<Data>) t.getModels(Data.class);
        datas.add(data);
        for(Data data2 : datas) {
            System.out.println(data2);
        }

        ArrayList<Magic> magics = (ArrayList<Magic>) t.getModels(Magic.class);
        magics.add(magic);
        for(Magic magic2 : magics) {
            System.out.println(magic2);
        }

    }

}

Another possibility to use the same things without parameter since we don't use it inside the method

public class Tester {

    private <T> ArrayList<T> getModel() {
        ArrayList<T> arrayList = new ArrayList<T>();
        return arrayList;
    }


    public static void main(String[] args) {
        Data data = new Data(12, "test_12");
        Magic magic = new Magic(123, "test_123");

        Tester t = new Tester();

        ArrayList<Data> datas =  t.getModel();
        datas.add(data);
        for(Data data2 : datas) {
            System.out.println(data2);
        }

        ArrayList<Magic> magics = t.getModel();
        magics.add(magic);
        for(Magic magic2 : magics) {
            System.out.println(magic2);
        }

    }

}

Model class (Data)

public class Data {

    private Integer id;
    private String name;


    public Data() {
    }


    public Data(Integer id, String name) {
        super();
        this.id = id;
        this.name = name;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    @Override
    public String toString() {
        return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
    }

}

Model class (Magic)

public class Magic {

    private Integer id;
    private String name;


    public Magic() {
    }


    public Magic(Integer id, String name) {
        super();
        this.id = id;
        this.name = name;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    @Override
    public String toString() {
        return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
    }

}
Sign up to request clarification or add additional context in comments.

4 Comments

You don't even need the Class<T> parameter, since it's never used. Just leave it off and the type will be inferred from the call site. Of course, then you've just reinvented Guava's Lists.newArrayList() method.
@Festus where you are casting the class type ? i.e Class<T> type ?
you are not using type. Why not declare it as private <T> ArrayList<T> getModels()?
@FestusTamakloe: yeah, it is possible that the compiler will have issues inferring T in some cases if you remove that parameter, but the caller can always explicitly specify it
2

This works:

private void getModel(){
   ArrayList<?> arrayList = new ArrayList<Object>();
}

I mean, it is unclear what you are trying to do. Generics is purely compile-timem, to perform compile-time type checking. Therefore, if the type parameter is not known at compile time, it would be useless.

Comments

0

Try using following

public <T> List<T> getList(Class<T> requiredType) {
    return new ArrayList<T>();
}

public void useList() {
    List<Integer> ints = getList(Integer.class);
    List<String> lists = getList(String.class);
}

2 Comments

well in this case, you are not using requiredType. Why not just declare it as public <T> List<T> getList()?
if you have a scenario where you are aware of the class type of the object (may be you are loading some data from a file which has class name info etc) then the above method would be useful. Because otherwise you will have to cast to the correct type with if/else checks. But you are right .. other than in such a scenario we can simply have T or simply need not have a method like this at all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.