Java 基本类型的包装类介绍

基本包装类为什么存在

将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据
一般操作:(比如:Integer)类提供了多个方法,在int和String之间相互转化

一般字段
static int MAX_VALUE   //它的值为2^31 - 1(int最大值)
static int MIN_VALUE   //它的值为-2^31(int最小值)
static int SIZE    //二进制补码表示int的比特位数
static Class<Integer>  TYPE //表示基本类型int的Class实例
基本类型和包装类一一对应
byte     	Byte
short 		Short
int			Integer
float		Float
double		Double	
char		Character
boolean		Boolean
Integer 转进制
int a = 0;
Integer.toBinargString(a);//转二进制
Integer.toOctalString(a);//转八进制
Integer.toHexString(a);//转十六进制
构造方法
//Integer(int a)
Integer i = new Integer(66);
//Integer(String str)
Integer i = new Integer("66");
Integer i = new Integer("abd");//报错 非法 不能转化
int 和String 的转化
//int 转 String
int i = 100;
//方法一:
String s1 = i+ "";
//方法二:
String s2 = String.valueOf(i);
//方法三:
Integer i3 = new integer(i);//先将int转化为 Integer 在转化为String
String s3 = i2.toString();
//方法四:
String s4 = Integer.toString(i);//使用了Integer的方法来转化为字符串
//String 转 int
String s = "200";
//方法一:
Integer i = new Integer(s);
int _i = i.intValue();
//方法二:
int i = Integer.parseInt(s);
// 基本数据类型有8种,而其中有七种都有parseXxx()方法将字符串转化为基本数据类型  (只有char 的 包装类没有,因为 如果有字符串和char 的转化通过toCharArray()转化成字符数组)
JDK5新特性
	* 自动装箱:把基本数据类型转化为包装类类型
	*  自动拆箱:把包装类类型转化为基本数据类型
//1.5前 没有自动装箱
int x = 100;
Integer i = new Integer(x);	//将基本数据类型包装为对象  装箱
int y = i.intValue();		//将对象转换为基本数据类型  拆箱
//1.5后 有了自动拆箱
 Integer i = 100;			//自动装箱 
 int y = i;					//自动拆箱
 //注意 :当i为null(空指针时) 是不能自动拆箱的。空指针异常
Integer 重写了equals 方法

***比较的是值 ***
但是 当自动装箱时,如果是在-128到127的byte的取值范围,自动装箱不会创建新数组,而是从常量池(从数组中取)中去取,超过了就要再新创建对象。
byte 0 为 -128 255 为 127

Integer i = new Integer(100);
Integer i2 = new Integer(100);
i == i2;//(false)
i.equals(i2);//(true)

Integer i = 100;
Integer i2 = 100;
i == i2;//(true)
i.equals(i2)//true

Integer i = 128;
Integer i2 =  128;
i == i2 ; //false
i.equals(i2);//true

猜你喜欢

转载自blog.csdn.net/qq_40435621/article/details/84312211