Beginner's mistake of using Object as parameter
Consider writing a method that takes an array of objects and a collection and puts all objects in the array into the collection. So we try to implement it .
Here is a first attempt:
By now, you will have learned to avoid the beginner’s mistake of trying to use Collection<Object>.
Now we can have method as :
Notice that we don’t have to pass an actual type argument to a generic method. The compiler infers the type argument for us, based on the types of the actual arguments. It will generally infer the most specific type argument that will make the call type-correct.
See this for more:
Expressing dependencies in type parameters : Wildcards vs bounded type parameters
Consider writing a method that takes an array of objects and a collection and puts all objects in the array into the collection. So we try to implement it .
Here is a first attempt:
static void fromArrayToCollection(Object[] a, Collection<?> c) {
for (Object o : a) {
c.add(o); // compile time error
}
}
By now, you will have learned to avoid the beginner’s mistake of trying to use Collection<Object>.
static void fromArrayToCollection(T[] a, Collection<T> c) {
for (Object o : a) {
c.add(o); // works fine this time
}
}
Now we can have method as :
Object[] objectArray = new Object[100];
Collection<Object> collObject = new ArrayList<Object>();
fromArrayToCollection(objectArray , collObject );// T inferred to be Object
String[] stringArr = new String[100];Also see here for clearer picture on Using type parameter as Object.
Collection<String> collString = new ArrayList<String>();
fromArrayToCollection(stringArr , collString );// T inferred to be String
fromArrayToCollection(stringArr , co);// T inferred to be Object
Integer[] ia = new Integer[100];
Float[] fa = new Float[100];
Number[] na = new Number[100];
Collection<Number> cn = new ArrayList<Number>();
fromArrayToCollection(ia, cn);// T inferred to be Number
fromArrayToCollection(fa, cn);// T inferred to be Number
fromArrayToCollection(na, cn);// T inferred to be Number
fromArrayToCollection(na, co);// T inferred to be Object
fromArrayToCollection(na, cs);// compile-time error
Notice that we don’t have to pass an actual type argument to a generic method. The compiler infers the type argument for us, based on the types of the actual arguments. It will generally infer the most specific type argument that will make the call type-correct.
See this for more:
Expressing dependencies in type parameters : Wildcards vs bounded type parameters
No comments:
Post a Comment