The question had been asked to me in an interview.
I know that primitive types will be converted into wrapper class object to store in any data structure.
But interviewer asked me I dont want it to be a wrapper class object and it should be stored as primitive type.
How can we do that?
Using Java's Collection API, you cannot do it in a sensible way. Of course you could implement the List
or Map
interfaces yourself and decide to store primitives instead of objects but that would cause you a headache anyway. Java's collection interfaces are all based on objects (Generics don't even play a role in that), so you cannot have an add
or remove
method that takes an int as its argument.
Let's say you have your own implementation of List<Integer>
that stores int
instead of the Integer
defined by the interface, you could write something like this:
List<Integer> intList = new MyPrimitiveImplementation<>();
intList.add(42);
Now what happens is that the primitive int 42 gets autoboxed to an Integer
object because the Collection
interface defines the add method as add(Integer e)
. What your implementation could then do would be unboxing the Integer
object again just to get the primitive back.
So, there's really no point. You either get serious performance trouble (imagine the above autoboxing happening a couple million times), or you lose compatibility with the Collections API. Both are undesirable.
You can implement the interfaces List
, Set
and Map
however you like. Therefore it would be perfectly possible to write an implementation of List<Integer>
, for example, where all the items are stored internally as primitive int
values. However, if you use the most common implementations of these interfaces (ArrayList
, HashSet
and HashMap
) all of the values will be stored internally as Objects
(which include boxed primitives like Integer
as well as array types like int[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With