0

I want to write a method that will create a List of the type I define in the method parameters. So if I have 3 classes: Student, Teacher and Janitor, the method should create a List of whatever type is passed in

public void methodName(TYPE){  
    List<TYPE> results = new List<TYPE>();  
}

What should I be using for TYPE?

Sionnach733
  • 4,686
  • 4
  • 36
  • 51

4 Answers4

1

You can use JAVA generics. One way is to allow all class types to be acceptable, by this..

public <T> void methodName(Class<T> cl){  
    List<T> results = new ArrayList<T>();  
}

or a better way would be to make all classes you want to be accepted derive from an interface, say Person and then you can do..

public <T extends Person> void methodName(Class<T> cl){  
    List<T> results = new ArrayList<T>();  
}

This limits the set of classes accepted by the the method, to only those implementing Person.

vidit
  • 6,293
  • 3
  • 32
  • 50
0

It's not entirely clear what you want, but one option is as follows:

public <T>
void methodName(Class<T> clazz) {

    List<T> results = new ArrayList<T>();
    ...
}

You could then call it as:

methodName(Student.class);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

If these three classes can inherit from a single class or implement a single interface then your method signature can be like this:

public List<ParentClass/Interface> methodName(TYPE);

If three class cannot be related to a common contract as mentioned above then other choice will be to return the list of Objects and cast the objects appropriately when you iterate the list of objects:

public List<Object> methodName(TYPE);
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

You may want to check out a question of mine, which, however, approaches the issue from the other side.

Basically Java has such a function already (feel free to go from there):

Collections.<String>emptyList()

to get an empty List with elements which are supposedly of type String. Java's source looks like this:

public static final List EMPTY_LIST = new EmptyList<Object>();
:
public static final <T> List<T> emptyList() {
  return (List<T>) EMPTY_LIST;
}
Community
  • 1
  • 1
sjngm
  • 12,423
  • 14
  • 84
  • 114