java - How can I store primitive types in Hashmap or list as a value instead of a wrapper class object -
the question had been asked me in interview.
i know primitive types converted wrapper class object store in data structure.
but interviewer asked me dont want wrapper class object , should stored primitive type.
how can that?
using java's collection api, cannot in sensible way. of course implement list
or map
interfaces , decide store primitives instead of objects cause headache anyway. java's collection interfaces based on objects (generics don't play role in that), cannot have add
or remove
method takes int argument.
let's have own implementation of list<integer>
stores int
instead of integer
defined interface, write this:
list<integer> intlist = new myprimitiveimplementation<>(); intlist.add(42);
now happens primitive int 42 gets autoboxed integer
object because collection
interface defines add method add(integer e)
. implementation unboxing integer
object again primitive back.
so, there's no point. either serious performance trouble (imagine above autoboxing happening couple million times), or lose compatibility collections api. both undesirable.
Comments
Post a Comment