Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 915
akf Avatar asked Sep 29 '09 22:09

akf


People also ask

Why do you compile?

Compiling allows the computer to run and understand the program without the need of the programming software used to create it. When a program is compiled it is often compiled for a specific platform (e.g., IBM platform) that works with IBM compatible computers, but not other platforms (e.g., Apple platform).

What does compile mean in it?

Compile refers to the act of converting programs written in high level programming language, which is understandable and written by humans, into a low level binary language understood only by the computer.

What does it mean to compile files?

to put together (documents, selections, or other materials) in one book or work. 2. to make (a book, writing, or the like) of materials from various sources.

Why do we compile in C?

C is a mid-level language and it needs a compiler to convert it into an executable code so that the program can be run on our machine.


1 Answers

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

like image 184
skaffman Avatar answered Nov 15 '22 18:11

skaffman