0

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.

0

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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.