Reputation: 485
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.
Upvotes: 0
Views: 101
Reputation: 3469
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
Upvotes: 2