Monday, July 29

ITEM 25: PREFER LISTS TO ARRAYS

                             PREFER LISTS TO ARRAYS


Reason:

Lists, if implemented correctly, can save us from ClassCastException but arrays can not.

How does that happen ?

lets start it with a statement

List in invariant while arrays are covariant .

Now what is this invariant covariant difference

read the difference quickly here

http://efectivejava.blogspot.in/2013/07/what-is-covarient-and-invarient.html

Let's go through a simple example

Let's declare and instantiate an array

Object[] objectArray = new Integer[1];

assign a string value to first place in array

objectArray[0] = "str";

What happens here. This does not fail at compile time although it will throw arrayStoreException at runtime

Now let us declare and instantiate a list

List<Object> ol = new ArrayList<Integer>();

assign a string value to first place in list
ol.add("str");

what happens here. It won't compile at all. Compiler will complain You can not store String in Integer type list. So it is providing opportunity to amend the program at compile time itself instead of having a surprised burst at runtime.


Conclusively Arrays provide runtime type safety while List provides compile time type safety and we always wish to identify the error at earliest opportunity. So List should be preferred over Arrays from type safety perspective although on performance scale there can be different views depending upon the specific scenario and uage in code.

No comments:

Post a Comment