Java进阶包装类
Posted Ricky_0528
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java进阶包装类相关的知识,希望对你有一定的参考价值。
文章目录
1 包装类与基本数据类
基本类型 | 对应的包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
2 包装类的常用方法
所有的包装类都在java.lang
这个包中
Character和Boolean都继承自Object类,其余的数字类型都继承自Number类
方法非常多,使用时可以查看API文档
3 基本数据类型和包装类之间的转换
装箱:基本数据类型 ----> 包装类
拆箱:包装类 ----> 基本数据类型
package com.ricky.wrap;
public class WrapTest
public static void main(String[] args)
// 装箱
// 1. 自动装箱
int t1 = 2;
Integer t2 = t1;
// 2. 手动装箱
Integer t3 = new Integer(t1);
// 拆箱
// 1. 自动拆箱
int t4 = t2;
// 2. 手动拆箱
int t5 = t3.intValue();
// 也可以拆箱为其它数据类型
double t6 = t2.doubleValue();
4 基本数据类型与字符串之间的转换
package com.ricky.wrap;
public class WrapTest
public static void main(String[] args)
// 基本数据类型转换为字符串
int t1 = 2;
String t2 = Integer.toString(t1);
// 字符串转化为基本数据类型
// 1. 包装类的parse方法
int t3 = Integer.parseInt(t2);
// 2. 包装类的valueOf 先将字符串转换为包装类,再由自动拆箱转为基本数据类型
int t4 = Integer.valueOf(t2);
5 默认值
基本类型 | 默认值 |
---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | ‘\\u0000’ |
boolean | false |
\\u:unicode编码
而包装类所有的默认值为null,如果在类中使用需要格外注意
6 对象常量池
package com.ricky.wrap;
public class WrapTest
public static void main(String[] args)
Integer one = new Integer(100);
Integer two = new Integer(100);
// 使用了两次new关键字,因此one和two指向的是两块不同的空间
System.out.println(one == two); // false
Integer three = 100; // 自动装箱
// three自动拆箱
System.out.println(three == 100); // true
Integer four = 100;
// 相当于执行了Integer four = Integer.valueOf(100);
// Java为了提高程序执行的效率,对于[-128, 127]之间的数,如果在缓存区(对象池)中有就会直接产生,没有才会实例化Integer
System.out.println(three == four); // true
Integer five = 200;
System.out.println(five == 200); // true
Integer six = 200;
// 不在[128, 127]之间
System.out.println(five == six); // false
注意:所有的包装类除了Float和Double,都可以应用对象常量池
以上是关于Java进阶包装类的主要内容,如果未能解决你的问题,请参考以下文章