Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top