Java中包装类作用及注意点

Java中对每种基本类型都有一个对应的包装类,这里主要讲解包装类的作用和包装类使用时的一些注意点。

包装类的作用

作用主要有以下两方面:
- 编码过程中只接收对象的情况,比如List中只能存入对象,不能存入基本数据类型;比如一个方法的参数是Object时,不能传入基本数据类型,但可以传入对应的包装类;
- 方便类型之间的转换,比如String和int之间的转换可以通过int的包装类Integer来实现,具体如下。
int a = new Integer("123");
或者
int a = Integer.parseInt("123");

包装类使用时的注意点

这里先看一段代码:

public class StudyBox {
    public static void main(String[] args) {

        Integer a = 100, b = 100, c = 150, d = 150;
        Long e = 150l;
        System.out.println(a == b);
        System.out.println(c == d);
        System.out.println(c.equals(d));
        System.out.println(d.equals(e));
        System.out.println(e.equals(d));
    }

}

这段代码的输出结果如下:

true
false
true
false
false

第一个、第三个输出很好理解,但是其他三个输出可能就会让人有些疑惑。

代码解释

这里以int型对应的包装类Integer为例来说明:
在上段代码中,初始化Integer类型的a,是将int型数据100装箱然后赋值给变量a,其中装箱操作使用的是静态工厂方法valueOf(int i),下面我们看一下这个方法的源码:

/**
 * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

在这个方法注释的第二段中,说明了这个方法一定会缓存-128到127的值,也有可能会缓存这个范围以外的值,这就是上面代码中第二个输出是false的原因。即-128到127的值会被Integer类缓存起来(在Integer类中通过IntegerCache类来实现),从valueOf(int i)的代码中可以看出,对象a和b是同一个对象,所以==比较是true;而c和d是不同的对象,所以==比较是false。

另外,使用equals()来进行对象比较时,Integer会先检查类型是否一致,若不一致直接返回false,这也就是第四个和第五个输出false的原因。具体如以下源码:

public boolean equals(Object obj) {
     if (obj instanceof Integer) {
          return value == ((Integer)obj).intValue();
      }
      return false;
}
总结

以上内容若有错误之处,还请各位大神指点,不胜感激,同时也欢迎各位一起来探讨相关问题。

参考资料

解决Java包装类比较时遇到的问题

  • 20
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值