Something different between array and generics

arrays, generics, java

Solution

You can't change the type of an array (reference) at runtime. But you can compile code which tries to just fine.

String[] strings = new String[1];
Object[] objects = strings;
objects[0] = new Integer(1); // RUN-TIME FAILURE

When you compile your application, no error will be thrown by the compiler.

On the other hand, if you use generics, this WILL give you an error when you compile (build) your application.

ArrayList<String> a = new ArrayList<String>();
a.add(5); //Adding an integer to a String ArrayList - compile-time failure

In other words, you don't need to actually run your application and execute that section of code to find the problem.

Note, compile time failures are preferable to run time failures, since you find out about the problem before you release it to users (after which it's too late)!

Problem

I just read 《Effective Java》and I saw a sentence which said that As a consequence, arrays provide runtime type safety but not compile-time type safety and vice versa for generics I don't quite clear about it and I'm confused even after I've read all the examples given.Can anyone explain this to me,thanks a million.

Original source