Say I have an ArrayList that I have cast to an ArrayList of objects. I know that all the objects that were in the ArrayList I cast were of the same type, but not what the type w
Nope, type erasure makes sure of that.
As Jeffrey mentioned, this is impossible due to magics of type erasure. Your best choice I guess is to add an additional case for the empty list:
if (list.isEmpty()) {
// process empty ...
} else {
Object o = list.get(0);
if (o instanceof Integer) {
List<Integer> integers = (List<Integer>) list;
// process Integer ...
} else if (o instanceof String) {
List<String> strings = (List<String>) list;
// process String ...
} // etc...
}
But beware! This instanceof
chain is not generally considered good OO practice. Rather than passing around bare lists and then trying to guess their constituent types consider creating a wrapper class for the lists which may also hold a reference to a Class
object. That way you may also be able to refactor your different processing algorithms as overriding a single process()
method...