基本数据类型包装类
- 包装类?
java 给每种基本数据类型提供了包装类,用类来封装基本数据类型,并提供了一些便捷的方法供我们使用
-
八大数据类型的包装类
基本数据类型 包装类 byte Byte short Short int Integer long Long float Float double Double boolean Boolean char Character int的包装类的写法为Integer、char的包装类的写法是:Character
其余基本数据类型的包装类均是基本类型的首字母大写。
-
装箱 : 把基本数据类型包装为对应的包装类对象
-
// int ==》 Integer Integer i1 = new Integer(1); Integer i4 = new Integer(1); Integer i2 = Integer.valueOf(1); Integer i5 = Integer.valueOf(1); Integer i3 =1; System.out.println(i2==i5); //true System.out.println(i1==i4); //false System.out.println(i1==i2); //false System.out.println(i1==i3); //false System.out.println(i2==i3); //true
i2 ==i3 说明,自动装箱,底层调用的是 valueOf()方法;
valueOf()源码
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
IntegerCache 在这个数组里面存有值为-128到127的Integer类的实例,如果调用valueOf方法时,所取的值在这个范围里面,那么就可以直接从cache里面拿取相应的类,而不用新new一个,从而减小开销; cache数组范围可以在启动时调节jvm参数设置;
若超出范围,就重新new 一个新对象 ,也就说跟直接使用构造函数效果类似;
普通构造源码:
public Integer(int value) { this.value = value; }
这也就解释了为啥 上面i1 != i4了, 构造了两个对象,而非拿IntegerCache数组里的值;
-
-
拆箱 :把包装类对象转换为对应的基本数据类型。
-
int a = i1.intValue(); int a = i1; //自动拆箱
-
jdk1.5开始 ,提供了自动装箱,拆箱的语法糖 ,即 将基本数据类型和包装类型直接用等号连接 ;
-
与字符串的相互转换
-
//String ==> int String str = "12"; int i = Integer.parseInt(str); int j =new Integer(str); //本质上也是在构造函数里调用parseInt()方法 System.out.println(i); System.out.println(j); //int ==>String String s = Integer.toString(i); System.out.println(s); String s1 = String.valueOf(i); System.out.println(s1);
-
大整数与大小数
- BigInteger 与 BigDecimal
- 大整数与大小数用于处理超出java基本数据类型范围的数字,java中 Long 为8个字节,最高可存2*64-1 ,超出的数字从二进制的角度,会只截取后64位
- 大整数和大小数可以存无数位
- 大小数还可解决精度丢失的问题
- 推荐构造时传 String 参数
BigInteger 大整数类
-
这里用求阶乘的例子说明
public class Test { static BigInteger big =new BigInteger("1"); public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("输入一个数:"); String n = input.next(); System.out.println(ac(new BigInteger(n))); } private static BigInteger ac(BigInteger bigInteger) { if(bigInteger.equals(big)){ return new BigInteger("1"); } return ac(bigInteger.subtract(big)).multiply(bigInteger); } }
BigDecimal 大小数类
- 使用:
//普通的double 精度丢失
double a = 0.2;
double b = 0.1;
System.out.println(a+b); // 0.30000000000000004
BigDecimal bigDecimal1 = new BigDecimal("0.1");
BigDecimal bigDecimal2 = new BigDecimal("0.2");
BigDecimal add = bigDecimal1.add(bigDecimal2);
System.out.println(add); // 0.3
BigDecimal subtract = bigDecimal1.subtract(bigDecimal2);
System.out.println(subtract); // -0.1
BigDecimal multiply = bigDecimal1.multiply(bigDecimal2);
System.out.println(multiply); // 0.02
BigDecimal divide = bigDecimal1.divide(bigDecimal2);
System.out.println(divide); // 0.5
//BigDecimal 可以用 BigInteger 来构造,反过来不行
BigInteger bigInteger1 = new BigInteger("123");
BigDecimal bigDecimal3 = new BigDecimal(bigInteger1);
System.out.println(bigDecimal3);