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.

Avi Patel
  • 475
  • 6
  • 23
  • 1
    Possible duplicate of [What is the Collections.checkedList() call for in java?](https://stackoverflow.com/questions/1161176/what-is-the-collections-checkedlist-call-for-in-java) and https://stackoverflow.com/a/1161243/1527544 – Antoniossss Sep 04 '18 at 08: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 – Andy Turner Sep 04 '18 at 08:34
  • I want casting type of thing. because what i want is to convert this generic list into appropriate class. – Avi Patel Sep 04 '18 at 09:08

1 Answers1

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

Jay Dangar
  • 3,271
  • 1
  • 16
  • 35