为什么允许将基本数据类型添加到ArrayList? [英] Why is it allowed to add primitive datatypes to an ArrayList?

查看:298
本文介绍了为什么允许将基本数据类型添加到ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以将一个Integer对象添加到整数类型的 ArrayList 中。这对我来说很有意义。像这样:

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));

但为什么可以添加像int这样的基本数据类型而不是 Integer ?像这样:

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);

为什么允许?

推荐答案

这称为 自动装箱 。对于具有相应原语的类(例如, Long - > long Integer - > int ),Java将为您处理转换。

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. 表现惩罚;
  2. 角落案例:when null 被解除封装到一个原语中,将抛出一个 NullPointerException ,这对程序员来说可能是意想不到的,因为它看起来像一个基元抛出异常。

  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.

这篇关于为什么允许将基本数据类型添加到ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆