gabi
gabi

Reputation: 1113

Java function to set unknown type of arraylist

I want to be able to create ArrayList of unknown type in order to fill spinner
I have the following method, but I missed the correct syntax type..
I need to pass it the class type (for example "Person"), the spinner id and the array of the classes ("Person[]").

private void fillSpinner(Class clss, int id, Class[] c_array) {
    List<clss> list = new ArrayList<clss>();
    for (clss c : c_array) {
        list.add(c);
    }
}

the c_array type should be the type of clss.
for example - calling to this methos should be:

Person[] persons = ....
fillSpinner(Person, R.id.person_spinner, persons)

What am I missing?

Thanks.

Upvotes: 0

Views: 495

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You need to make the method Generic and you don't need the first parameter:

private <T> void fillSpinner(int id, T[] array) {
    List<T> list = new ArrayList<T>();
    for (T t : array) {
        list.add(t);
    }
}

Then, you will be able to provide the Generic type for the method like this:

Person[] persons = ....
fillSpinner<Person>(R.id.person_spinner, persons)

Upvotes: 3

Smutje
Smutje

Reputation: 18143

private <T> void fillSpinner(int id, T[] c_array) {
    List<T> list = new ArrayList<T>();
    for (T c : c_array) {
        list.add(c);
    }
}

Upvotes: 2

Related Questions