包装类

包装类

包装类方便我们操作基本数据类型中的数据
例如:
要得到int的最大值,最小值,就可以用包装类中的属性:
Integer.MAX_VALUE;
Integer.MIN_VALUE;
要得到int数字进制转换,转成2,8,16进制可以用包装类中的方法
toBinaryString(int i) 十进制转2进制
tohexString(int i)十进制转16进制
toOctalString(int i)十进制转8进制

包装分类

原始数据类型和包装类对照表
原始数据类型 包装类
boolean(布尔型) Boolean
byte(字节型) Byte
char(字符型) Character
short(短整型) Short
int(整型) Integer
long(长整型) Long
float(单精度浮点型) Float
double(双精度浮点型) Double

包装转换

基本数据类型————字符串
+字符串连接
int i=10;
String str =i+"";—>’‘10’’;
String里有方法
String str2=String.ValueOf(i);—>’‘10’’;
包装类完成
Integer inte1=new Integer(3);
inte1.toString();
字符串————基本数据类型
Integer its=new Integer(“20”);
int age=its.intValue();
字符串必须是数字,否则报NumbmerFormatException
包装类————基本数据类型
Integer it1=new Integer(“1”);
int l=it1.intVvalue();

自动拆箱与自动装箱

自动装箱(基本数据类型转换成包装类)
Integer p=4;
自动拆箱
int b=p;
int b=p+5;

== 比较的是地址

Integer ll =new Integer(“30”);
Integer lk=new Integer(“30”);
System.out.println(ll==lk);false

包装类中的equals()方法

包装类重写Object中的equals()方法,比较的是值
Integer h=new Integer(“20”);
Integer k=new Integer(“20”);
System.out.println(h==k);true

包装类中的compareTo()方法

public int compareTo(Integer anotherInteger)
Integer a1=new Integer(“40”);
Integer a2=new Integer(“40”);
System.out.println(a1.compareTo(a2));
a1的值==a2, 返回0
a1的值<a2,返回负数
a1的值>a2,返回正数

包装类中自动拆箱和装箱的注意事项

以前:
Integer c1=new Integer(127);
Integer c2=new Integer(127);
System.out.println(c1==c2);//false 比较的是地址
System.out.println(c1.equals(c2));//true 比较的是值

拆箱:
Integer c3=128;//超过127 相当于Integer c3=new Integer(128);
Integer c4=128;//超过127 相当于Integer c4=new Integer(128);
System.out.println(c3==c4);//false
System.out.println(c3.equals(c4));//true

Integer c5=127;
Integer c6=127;
System.out.println(c5==c6);//true
System.out.println(c5.equals(c6));//true

只要是一个字节(-128~127)的大小,那么数据就被共享,不会在内存中开辟新的空间,超过这个范围就不会被共享了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值