Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No error with this collection declared with generics?

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);
like image 500
emilly Avatar asked Jan 06 '13 13:01

emilly


2 Answers

The first code snippet does not result in a compile time error, because at the line

c.add(123)

the compiler inspects the type of c. Since you declared c as Collection, the compiler treats it as such. Since Collection offers a method add(Object), it is perfectly reasonable to add any 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 Collection it deals with is an Collection<String>, which can only accept Strings. Thus, there is no method add(int) or add(Object), only add(String). This leads to a compile-time error.

like image 112
Alexander Weinert Avatar answered Sep 16 '22 15:09

Alexander Weinert


why it did not throw compile time error?

Because it's not syntactically or semantically invalid, it's just unwise.

Note that most modern IDEs (e.g. Eclipse) can be configured to warn you about the unparameterised Collection c, and optionally to fail to compile.

like image 41
Oliver Charlesworth Avatar answered Sep 17 '22 15:09

Oliver Charlesworth