0

I have generic ArrayList that i am setting up on ArrayAdapter which is also a generic type adapter. Now, i want to convert ArrayList<?> to ArrayList<MyClass>. I have searched alot, but could not figure it out. thanks for the help.

I have these 2 generic type adapters and lists.

private ArrayAdapter<?> GeneralAdapter;
private ArrayList<?> GeneralList;

I am setting this adapter on Listview. and Adding different types of class into list dynamically.like

GeneralList<State>
GeneralList<District>

after setting up this lists i am updating adapter using notifydatasetchanged().

I just need to now convert this GeneralList into ArrayList,ArrayList as i need. I am adding items one at a time and for using it again for other class i clear generalList and then set it up for another class.

3
  • 1
    Possible duplicate of What is the Collections.checkedList() call for in java? and stackoverflow.com/a/1161243/1527544 Commented Sep 4, 2018 at 8:14
  • 1
    What exactly do you mean by "convert"? Do you mean "cast"? Do you mean "make a view"? Do you mean "make a new list with only the State elements?" etc Commented Sep 4, 2018 at 8:34
  • I want casting type of thing. because what i want is to convert this generic list into appropriate class. Commented Sep 4, 2018 at 9:08

1 Answer 1

2

using dynamic casting you can achieve this.

If you want List of States from GeneralList, then ->

List<State> states = filter(State.class, GeneralList);

this is your filter function ->

static <T> List<T> filter(Class<T> clazz, List<?> items) {
        return items.stream()
                .filter(clazz::isInstance)
                .map(clazz::cast)
                .collect(Collectors.toList());
}

Source -> dynamic Casting in Java

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

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.