Why is it allowed to add primitive datatypes to an

2020-04-11 06:59发布

I understand that it is possible to add an Integer Object to an ArrayList of type Integer. That makes sense to me. Like this:

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(3));

But why is it possible to add a primitive datatype like int instead of Integer? Like this:

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);

Why is that allowed??

1条回答
【Aperson】
2楼-- · 2020-04-11 07:31

This is called autoboxing. For classes that have corresponding primitives (e.g, Long -> long, Integer -> int), Java will handle the conversion for you.

It should be noted this behavior comes with some dark corners:

  1. a performance penalty;
  2. Corner cases: when null is unboxed into a primitive, a NullPointerException will be thrown, which might be unexpected for the programmer since it looks like a primitive is throwing the exception.
查看更多
登录 后发表回答