Jdk 1.5

I am copying a small snippet from generics..

static void fromArrayToCollection(Object[] a, Collection<?> c) {

for (Object o : a) {

c.add(o); // Compile time error

}

}

Rule 1

In the tutorial they are saying that "We can call this method with any kind of collection whose element type is a supertype of the element type of the array."

Rule 2

But In the same tutorial they are saying that Collection<Object> will not accept a <String > since both are different ....

I am totally confused about the two statements. How does the first code snippet confirms to rule 2?

[648 byte] By [Bulla] at [2007-10-3 4:41:01]
# 1

Collection<?> means a collection with any parameter type. For example it could be a list of Strings.

The array of objects may contain any kind of objects, for example Integers.

Therefore c.add(o) blindly adds an object from the array to the collection, that is, a number to a list of strings.

Do you now see why c.add(o) is wrong?

jsalonena at 2007-7-14 22:45:04 > top of Java-index,Java Essentials,Java Programming...