未分类
2020-08-19 15:25:11
1822677238@qq.com
手机扫码查看
包装类
什么是包装类?
基本数据类型所对应的引用数据类型。
Object可统一所有数据,包装类的默认值是null
public class demos{
public static void main(String[] args) {
Byte b1=new Byte(10);
System.out.println(b1);
}
}
class Byte{
byte value;
public Byte(byte value) {
this.value = value;
}
public Byte(int value) {
this.value = (byte)value;
}
@Override
public String toString(){
return this.value+"";
}
}
包装类对应
基本数据类型 包装类型 byte Byte short Short int Integer long Long float Float double Double boolean Boolean char Character
类型转换与装箱、拆箱
8个包装类提供不同类型的转换
//将包装类型转换为基本类型
Short s=new Short("10");
byte b1=s.byteValue();
short s2=s.shortValue();
int i=s.intValue();
long l=s.longValue();
double d=s.doubleValue();
float f=s.floatValue();
parseXXX()静态方法
//将字符串转换成byte
byte b=Byte.parseByte("123");
byte b2=new Byte("123").byteValue();
valueOf()静态方法
//valueOf()
Byte b3=Byte.valueOf((byte)123);
//ERROR java.util.lang.NumberFormatException异常
Byte b4=new Byte("1a2b3c");
注意:需保证类型兼容,否则抛出java.util.lang.NumberFormatException异常
JDK5.0之后,自动装箱、拆箱。基本数据类型和包装类自动转换
整数缓冲区
java预先创建了256个常用的整数包装类型对象
在实际应用中,对已创建的对象进行复用
short缓存区
static final Short cache[] =new Short[-(-128)+127+1];//256
static {
for(int i=0;i<cache.length;i++){
cache[i]=new Short((short)(i-128));
}
}
public static Short valueOf(short s) {
final int offset = 128;
int sAsInt = s;
if (sAsInt >= -128 && sAsInt <= 127) { // must cache
return ShortCache.cache[sAsInt + offset];
}
return new Short(s);
}
- 本页地址 https://www.9713job.com/?p=2132
- 上一篇 <<2020java教程:Object类
- 下一篇 >>2020java教程:Sting类



发表回复