java - Why is it allowed to add primitive datatypes to an ArrayList? -
i understand possible add integer object arraylist of type integer. makes sense me. this:
arraylist<integer> list = new arraylist<integer>(); list.add(new integer(3)); but why possible add primitive datatype int instead of integer? this:
arraylist<integer> list = new arraylist<integer>(); list.add(3); why allowed??
this called autoboxing. classes have corresponding primitives (e.g, long -> long, integer -> int), java handle conversion you.
it should noted behavior comes dark corners:
- a performance penalty;
- corner cases: when
nullunboxed primitive,nullpointerexceptionthrown, might unexpected programmer since looks primitive throwing exception.
Comments
Post a Comment