akf
akf

Reputation: 39485

Why does this compile?

I was taken aback earlier today when debugging some code to find that something like the following does not throw a compile-time exception:

 public Test () { 
     HashMap map = (HashMap) getList(); 
 }

 private List getList(){
     return new ArrayList();
 }

As you can imagine, a ClassCastException is thrown at runtime, but can someone explain why the casting of a List to a HashMap is considered legal at compile time?

Upvotes: 18

Views: 585

Answers (2)

developmentalinsanity
developmentalinsanity

Reputation: 6229

For one thing List is an interface. There is no reason why there couldn't exist a subclass of HashMap which also implements the List interface. In this situation it would be perfectly valid.

Upvotes: 17

skaffman
skaffman

Reputation: 403461

Because conceivably getList() could be returning a subclass of HashMap which also implements List. Unlikely, yes, but possible, and therefore compilable.

Upvotes: 29

Related Questions