自动装箱和拆箱
有时需要将int这样的基本类型转换为引用类型对象;
基本数据类型的自动装箱,拆箱是J2SE 5.0提供的新功能,为打包基本数据类型提供了方便,但提供方便的同时隐藏了细节,建议在能够区分基本数据类型与引用类型的差别时再使用;
一个自动装箱的例子:
Integer i=10;相当于Integer i=new Integer(10);
进行编译时,编译器根据上下文判断是否进行自动装箱动作,在上例中变量i引用的是Integer类的实例;
同样的动作适用于boolean、byte、short、char、long、float、double等基本数据类型,分别使用对应的包装类型Boolean、Byte、Short、Character、Long、Float、Double;
J2SE 5.0中也可以自动拆箱,也就是将对象中的基本数据类型信息自动取出;
例如:
1 Integer m=10; 2 Int n=m; 3 //相当于n=m.intValue();
m变量在自动装箱为Integer的实例后,如果被赋值给一个int类型的变量n,则会自动转换为int类型再赋值;
在运算时,也可以进行自动装箱和拆箱;
如:
1 Integer i=10; 2 System.out.println(i+10); 3 System.out.println(i++);
1 public class AutoBoxDemo{ 2 public static void main(String[] args){ 3 int i=10; 4 double d=10.5; 5 6 //把基本类型赋值给引用类型 7 //基本类型会在编译时自动装箱 8 Integer num1=i; 9 Double num2=d;10 System.out.println(num1);11 System.out.println(num2);12 13 //把包装类(引用类型)赋值给基本类型14 //会自动做拆箱15 int j=num1;16 //int j=num1.intValue();17 double dd=num2;18 //int dd=num2.doubleValue();19 System.out.println(j);20 System.out.println(dd);21 22 Object o=i;23 System.out.println(o);24 Integer b=(Integer)o;25 System.out.println(b);26 }27 }
枚举类型
1 public enum Color{ 2 RED,BLUE,BLACK,YELLOW,GREEN; 3 }
Enmu很像特殊的class,实际上enum声明定义的类型就是一个类;
这些类都是类库中Enum类的子类(java.lang.Enum<E>),它们继承了Enum中许多有用的方法;
枚举值都是public static final的,也就是常量,因此枚举类中的枚举值应全部大写;
枚举类型是class,在枚举类型中有构造器,方法和字段,但枚举的构造器有很大的不同;
构造器只在构造枚举值的时候被调用;
构造器私有private,不允许有public构造器;
枚举值可以再switch语句中使用;
1 public class EnumDemo{ 2 public static void main(String []args){ 3 System.out.println(Color.RED); 4 Color[] colors=Color.values(); 5 for(Color c:colors){ 6 System.out.println("循环:"+c); 7 } 8 9 System.out.println(Person.P1);10 Person[] persons=Person.values();11 for(Person p:persons){12 System.out.println("循环:"+p);13 }14 15 Person p=Person.P3;16 switch(p){17 case P1:System.out.println("switch:"+Person.P1);break;18 case P2:System.out.println("switch:"+Person.P2);break;19 case P3:System.out.println("switch:"+Person.P3);break;20 }21 }22 }23 24 //当jvm去加载使用枚举类时,会预先创建多个枚举类型的对象供外部类使用25 //public static final Color RED=new Color();26 //public static final Color BLUE=new Color();27 //public static final Color YELLOW=new Color();28 enum Color{29 RED,BLUE,YELLOW;//枚举类型的值必须作为第一条语句出现30 //不能使用public31 //调用次数与枚举数相同32 /*public*/ private Color(){33 System.out.println("构造方法");34 }35 36 /*public String toString(){37 return "aa";38 }*/39 }40 41 //public static final Person P1=new Person("张三",30);42 //public static final Person P2=new Person("李四",20);43 //public static final Person P3=new Person("王五",18);44 enum Person{45 P1("张三",30),P2("李四",20),P3("王五",18);46 private String name;47 private int age;48 private Person(String name,int age){49 this.name=name;50 this.age=age;51 }52 public String toString(){53 return name+"--"+age;54 }55 }
原标题:Java学习 (十七)、自动装箱和拆箱,枚举类型
关键词:JAVA