I have below code snippet and this works fine. Shouldn’t it throw compile time error because I have defined c as ArrayList which will contain String object but I am adding Integer object. So why it did not throw compile time/Run time error?
Collection c = new ArrayList<String>();
c.add(123);
I know below will throw compile time error but why not above. Whats the logical difference between both these code snippet?
Collection<String>() c = new ArrayList();
c.add(123);
The first code snippet does not result in a compile time error, because at the line
the compiler inspects the type of c. Since you declared c as Collection, the compiler treats it as such. Since
Collectionoffers a methodadd(Object), it is perfectly reasonable toaddany object to the c, especially an integer. Note that this program will however result in a runtime-error, if you attempt to read back the collection values as Strings.In your second code snippet you provide more information for the compiler to work with. In this snippet it knows that the
Collectionit deals with is anCollection<String>, which can only acceptStrings. Thus, there is no methodadd(int)oradd(Object), onlyadd(String). This leads to a compile-time error.