I understand that the use and motive of both of them - isInstance - is the equivalent of the instanceOf instance time. But why do we have two ways? Why can't we have a generic instanceof keyword implementation that is suitable for both cases?
For example, so they are currently used:
1) InstanceOf
public Collection<String> extract(Collection<?> coll) {
Collection<String> result = new ArrayList<String>();
for (Object obj : coll) {
if (obj instanceof String) {
result.add((String) obj);
}
}
return result;
}
2) isInstance
public <T> Collection<T> extract(Collection<?> coll, Class<T> type) {
Collection<T> result = new ArrayList<T>();
for (Object obj : coll) {
if (type.isInstance(obj)) {
result.add((T) obj);
}
}
return result;
}
So my question is: why can't we have a generic implementation of the instanceof operator that satisfies the second example above, as shown below? (i.e. why can't it resolve the type at runtime?)
public <T> Collection<T> extract(Collection<?> coll, Class<T> type) {
Collection<T> result = new ArrayList<T>();
for (Object obj : coll) {
if (obj instanceof type) {
result.add((T) obj);
}
}
return result;
}
source
share