Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is backward compatibility maintained by not allowing primitive in generics in java

I know that Java does not allow primitive data types to be used in Generics, i.e

List<int> l  = new List<int>();

is not allowed.

I have read a related post which states that this is for the purpose of backward compatibility. Can anyone explain how not allowing primitives to be used in generics maintains backward compatibility? I would greatly appreciate a small explanation with an example.

One sub question: what is/are major/minor drawbacks of how generics are implemented in java.

Your response will be greatly appreciated.

like image 897
Prashant Shilimkar Avatar asked Nov 30 '13 04:11

Prashant Shilimkar


1 Answers

As explained here (with examples), generics in Java only exist at compile time. Under the hood, a generic collection is really a non-generic collection, and all their contents are stored as Object. In pre-generics times (pre Java 5), collections could not contain primitives because they cannot be down-casted to Object, and they still cannot.

To answer your question: Allowing generic collections to store primitives would not be a breaking change because generic collections did not exist previously, and thus the primitive decision has nothing to do with backward compatibility. If they decided to implement generics like in C#, primitive generic collection types would exist, and it would not change the behavior of previous programs.

The reasons as to why they implemented generics this way, though, might be related to the fact that this is a low-energy approach: They barely had to add any code to collections to support this feature, and they did not have to change the JVM. This improves maintainability. That does not sound like much of a reason, but it might actually be very important if you want every future JVM be able to still execute Java 1.0 code until the end of time.

like image 175
Domi Avatar answered Oct 07 '22 00:10

Domi