Iterates over generic arrays of any type in Java
If there are Java collection instances that can carry primitive types, generic arrays, and / or iteratable collections, I want to treat generic arrays as iteratable collections, but how? For example, the following pseudo java code
List<?> list1; list1.add(new int[2]); list1.add(new String[3]); list1.add(new ArrayList()); for (Object e : list1){ if (e instanceof Iterable){ //The int[2] and String[3] will not fall in this case that I want it be //Iterate within e } }
Please tell me how to make int [2] and string [3] fall in the case
Thank you & greetings, William
Solution
In the loop, you can use the appropriate array operands for instanceof
For int []:
if (e instanceof int[]) { // ... }
For object arrays (including string []):
if (e instanceof Object[]){ // ... }
Alternatively, when you add arrays to the main list, you can wrap each array in arrays In aslist() In this case, you can use list < list > generic instead of wildcard generic list And avoid using instanceof to check data types Something like this:
List<List> list1; list1.add(Arrays.asList(new int[2])); list1.add(Arrays.asList(new String[3])); list1.add(new ArrayList()); for (List e : list1){ // no need to check instanceof Iterable because we guarantee it's a List for (Object object : e) { // ... } }
Any time you use instanceof and generics together, it's a smell. You may be doing something wrong with your generics