Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store primitive types in Hashmap or list as a value instead of a wrapper class object

Tags:

java

core

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?

like image 725
Mallikarjuna Sangisetty Avatar asked Jan 09 '23 06:01

Mallikarjuna Sangisetty


2 Answers

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 intinstead 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.

like image 187
Flo Avatar answered Jan 11 '23 20:01

Flo


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[].

like image 31
Paul Boddington Avatar answered Jan 11 '23 20:01

Paul Boddington