If I use unbounded wildcard types for two collections (each collection will have a different type) as the arguments for a method:
private void doAssertion(List<?> testList, List<?> generatedList)
Inside this method, can I first check the type of objects in these collections, and then cast the collection to a parameterized type? This just smells bad, and I get an unchecked cast warning.
if (testList.get(0) instanceof X) {
List<X> xList = (List<X>) testList;
// call methods specific to X for each object
}
else if (testList.get(0) instanceof Y){
List<Y> yList = (List<Y>) testList;
// call methods specific to Y for each object
}
Part of my problem is that I don’t have the ability to touch the code that defines classes X or Y. Otherwise, I know I can have them implement a common interface, and use a bounded type parameter. I can’t overload assertEqual because both methods have the same erasure.
In my case, X and Y are always going to be children of other classes, and I’m not modifying the objects in anyway, just calling the get() methods of the objects.
Warning:
means list of unknown type. You will be able to get() from this list but will not be able to add() to it, except null.
In case you need to add elements it’s best to just use non-generic version and check the type as you proposed. The result will be the same.
Also make sure that lists are not empty before doing (testList.get(0) instanceof X)