Integer类的概念
java.lang.Integer 类是 int 类型的包装类,该类由 final 关键字修饰表示不能被继承.
该类重写了 equals( ) 方法,hashCode( ) 方法,to String( ) 方法.
常用的方法
- Integer( int value ) —根据参数指定的整数构造对象
- Integer( String s ) —根据参数指定的字符串构造对象
- int intValue( ) —用于获取调用对象中包装的整数数据并返回
- static Integer valueOf( int i ) —用于参数指定的整数得到 Integer 类型对象并返回
- static int parseInt( String s ) —用于将 String 类型转换为 int 类型
//1.实现Integer类型和int类型之间的转换
//Integer类型转换为int类型 ———— 拆箱机制
Integer it1 = new Integer(123);
int num = it1.intValue();
System.out.println("num = " + num); //打印结果为int类型的123
//int类型转换为Integer类型 ———— 装箱机制
Integer it3 = Integer.valueOf(num);
System.out.println("it3 = " + it3); //打印结果为String类型的123
//2.String类型转换为int类型
int res = Integer.parseInt("123");
System.out.println("res = " + res); //打印结果为int类型的23
装箱机制和拆箱机制
装箱主要指从int类型向Integer类型的转换过程
拆箱主要指从Integer类型向int类型的转换过程
从jdk1.5开始支持自动装箱和自动拆箱机制
自动装箱:Integer it1 = 20 ;
自动拆箱:int ia = it1 ;
自动装箱池
为提高效率在Integer类的内部提前将 -128 到 127 之间的所有整数装箱完毕并放入自动装箱池中,若程序中出现该范围的整数则直接从池中取出使用即可.
Integer it1 = 128;
Integer it2 = 128;
Integer it3 = new Integer(128);
Integer it4 = new Integer(128);
System.out.println(it1 == it2); //1.比较地址 false
System.out.println(it1.equals(it2)); //2.比较内容 true
System.out.println(it3 == it4); //3.比较地址 false
System.out.println(it3.equals(it4)); //4.比较内容 true
解析:it1 和 it2 为自动装箱的两个对象,因此 ti1 和 it2 的地址不同
Integer类重写了 equals( ) 方法,因此 it1 和 it2 以及 it3 和 it4 的内容相同
it3 和 it4 为分别构造的两个对象,因此地址不同
然而,若把上述代码中的128全部给为127,那么打印结果依次为:true , true , false , true . 这便运用了自动装箱池的概念,ti1 和 it2 为 127 ,那么它们便在自动装箱池中,因此它们的地址相同.