包装类的定义, 自动装箱拆箱
包装类, 基本类型, string 类之间的相互转化
- package wrapper;
- import org.junit.Test;
- /*
- * 包装类的使用:
- * 1. 八种基本数据类型对应八种包装类
- * 2. 基本数据类型, 包转类, string 的转化
- *
- *
- * */
- public class WrapperTest {
- Integer in = null;
- /*
- * 基本数据类型 -> 包装类: 调用包装类的构造器
- * */
- @Test
- public void test1() {
- int num1 = 10;
- Integer in1 = new Integer(num1);
- Integer in2 = new Integer("123");
- System.out.println(in1.toString());
- System.out.println(in2.toString());
- System.out.println(in);
- }
- /*
- * 包装类 -> 基本数据类型: 调用包装类的 xxxValue() 方法
- * */
- @Test
- public void test2() {
- int num1 = 10;
- Integer in1 = new Integer(num1);
- Integer in2 = new Integer("123");
- System.out.println(in1.intValue());
- System.out.println(in2.intValue());
- }
- /*
- * JDK 5.0 新特性: 自动装箱与自动拆箱
- *
- * */
- public void method(Object obj) {
- System.out.println(obj);
- }
- @Test
- public void test3() {
- int num = 10;
- method(num);
- // 自动装箱:
- int num1 = 10;
- Integer in1 = num1;
- // 自动拆箱:
- int num2 = in1;
- }
- /*
- * 基本数据类型, 包装类 ->Sting 类型
- *
- * */
- @Test
- public void test4() {
- int num1 = 10;
- // 方法 1
- String str1 = num1 + "";
- System.out.println(str1);
- // 方法 2
- String str2 = String.valueOf(num1);
- System.out.println(str2);
- // 方法 3
- Integer in = new Integer(num1);
- String str3 = String.valueOf(in);
- System.out.println(str3);
- }
- /*
- * String -> 基本数据类型, 包装类
- * 调用包装类的 parseXxx()
- * */
- @Test
- public void test5() {
- String str1 = "123";
- int num = Integer.parseInt(str1);
- System.out.println(num);
- }
- /*
- * 自动装箱的一些知识
- * Integer 有一个内部静态类 IntegerCache, 里面有一个数组 static final Integer cache[];
- * cache[i] 对应的就是 Integer(i) 对象, 自动装箱时就不用去 new 了, i 的范围是 [-128,127]
- * */
- @Test
- public void test6() {
- Integer m = 1;
- Integer n = 1;
- System.out.println(m == n);//true, 因为没有 new 新对象
- Integer x = 128;
- Integer y = 128;
- System.out.println(x == y);//false,new 了新对象
- }
- }
来源: http://www.bubuko.com/infodetail-3364850.html