Wrapper包装类
基本数据类型由于不是类,不能够使用java类库提供的大量方法,所以在设计上,我们为每一个基本数据类型都对应一个类,同时数据存储的范围不变,此时基本数据类型就具备了类的特点。
基本数据类型 | 包装类 |
---|---|
byte | Byte |
char | Character |
short | Short |
int | Integer |
long | Long |
double | Double |
float | Float |
boolean | Boolean |
继承关系
Character
Boolean
Byte,Short,Integer,Long,Double,Float
装箱
基本数据类型包装成包装类的实例
Integer i = 1;
实现方式
/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value;
/**
* Constructs a newly allocated {@code Integer} object that
* represents the specified {@code int} value.
*
* @param value the value to be represented by the
* {@code Integer} object.
*/
public Integer(int value) {
this.value = value;
}
/**
* 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);
}
解析过程:先执行valueOf方法,当条件满足的时候,会直接返回InterCache中的值,否则,会new
一个Integer
对象
拆箱
获取包装类对象中包装的基本数据类型变量
调用包装类的.xxxValue()方法
int i = Integer.intValue();
字符串和基本数据类型的相互转换
-
基本数据类型转换成字符串
-
通过空字符+基本数据类型
String str = "" + 10;
-
使用
String
类的静态方法valueOf
String str = String.valueOf(10);
-
先将基本类型装修对象,然后调用对象的
toString
方法Integer i = new Integer(10); String str = i.toString();
-
-
字符串转换成基本数据类型
-
调用各自的包装类的静态方法
String str = "100"; int i = Integer.parseInt(str);
-
直接
new
包装类int i = new Integer(str);
-
包装类和字符串相互转换
-
包装类转换成字符串
-
通过空字符+基本数据类型
String str = "" + i;
-
使用
String
类的静态方法valueOf
String str = String.valueOf(i);
-
调用对象的
toString
方法String str = i.toString();
-
-
字符串转换成包装类
-
通过new 包装类
Integer i = new Integer(str);
-
通过包装类的
valueOf
方法Integer i = Integer.valueOf(str);
-