面向对象高级篇
目录
基本类型包装类
在Java中,由于基本类型不是继承自Object,为了在泛型代码中可以支持基本类型,Java给每个基本类型都对应了 一个包装类型。
基本数据类型和对应的包装类:
| 基本数据类型 | 包装类 |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Charcater |
| boolean | Boolean |
装箱和拆箱:
public static void main(String[] args) {
//装箱操作
Integer i = new Integer(10);
}
自动装箱和自动拆箱:
包装类型支持自动装箱,我们可以直接将一个对应的基本类型值作为对应包装类型引用变量的值。
public static void main(String[] args) {
//装箱操作
Integer i = 10;
//是Integer i=Integer.valueOf(10)的简化
//拆箱操作
int a=i;
//是int a=i.intValue();的简化
}
得益于包装类型的自动装箱和自动拆箱,我们可以让包装类型轻松的参与到基本类型的运算中:
public static void main(String[] args) {
Integer i = 10;
int a=i*i;
System.out.println(a);
}
false和true:
因为包装类是一个类,不是基本类型,所以说两个不同的对象,是不相等的:
public static void main(String[] args) {
Integer a=new Integer(10);
Integer b=new Integer(10);
System.out.println(a == b);
}
//输出false
通过自动装箱转换的Integer对象,如果值相同,得到的会是同一个对象,这是因为InterCache会默认缓存-128~127之间的所有值,将这些值提前做成包装类在数组中存放。如果直接让-128~127之间的值自动装箱为Integer类型的对象,那么始终都会得到同一个对象。如果超出这个缓存范围,得到的就是不同对象false:
public static void main(String[] args) {
Integer a=127;
Integer b=127;
System.out.println(a == b);
//输出true
Integer c=128;
Integer d=128;
System.out.println(c == d);
//输出false
}
判断对象的值是否相等:
public static void main(String[] args) {
Integer a=new Integer(10);
Integer b=new Integer(10);
System.out.println(a.equals(b));
}
//输出true
包装类提供的方法:
包装类支持字符串直接转换:
public static void main(String[] args) {
String str="666";
Integer i=new Integer(str);
//Integer i=Integer.valueOf("666");有多种方法
//Integer i=Integer.parseInt("666");
System.out.println(i*10);
}
可以对十六进制和八进制的字符串进行解码,得到对应的int值:
public static void main(String[] args) {
Integer i=Integer.decode("0xA6");
System.out.println(i);
}
//输出166
也可以将十进制的整数转换为其他进制的字符串:
public static void main(String[] args) {
System.out.println("0x"+Integer.toHexString(166));
}
//输出0xa6
......
特殊包装类:
除了上面的几种基本类型包装类之外,还有两个比较特殊的包装类型。
BigInteger:
用于计算超大数字。
public static void main(String[] args) {
BigInteger i=BigInteger.valueOf(100);
BigInteger a=i.add(BigInteger.TEN); //100+10
System.out.println(a);
}
//输出110
public static void main(String[] args) {
BigInteger i=BigInteger.valueOf(Long.MAX_VALUE);
BigInteger a=i.multiply(BigInteger.valueOf(Long.MAX_VALUE));
System.out.println(i);
}
BigDecimal:
浮点类型精度有限,而BigDecimal可以实现小数的精确计算。
public static void main(String[] args) {
BigDecimal i=BigDecimal.valueOf(10);
i=i.divide(BigDecimal.valueOf(3),20, RoundingMode.CEILING);
//计算10/3的结果,精确到小数点后20位
//RoundingMode是舍入模式,就是精确到最后一位时该怎么处理,这里CEILING表示向上取整
System.out.println(i);
}
//输出3.33333333333333333334
1244

被折叠的 条评论
为什么被折叠?



