java 5.0学习笔记之一

来源:互联网 发布:世界银行数据库中文版 编辑:程序博客网 时间:2024/05/16 09:36

StringBuilderGenenic、for-eachAutobox and Unboxes

<!--[endif]-->

Enum Type


新类

StringBuilder
非线程同步的情况下可以替代
StringBuffer,速度会更快。

主要方法:Append(),insert()

接受参数:可以是任何可以转换为string的数据类型包括对象实例。

<!--[if !supportEmptyParas]--> <!--[endif]-->

<!--[if !supportEmptyParas]--> <!--[endif]-->

Genenic

Collection

:String type Collection

<!--[if !supportEmptyParas]--> <!--[endif]-->

for-each

for(Rank rank:a)

:for each Rank rank in a

可以用于Iterator或 Array循环中用于替代循环变量。如果在循环体中要使用Iterator或要改变其中的一个值则无法使用。

<!--[if !supportEmptyParas]--> <!--[endif]-->

Autobox and Unboxes

在对性能要求比较严格的情况下最好不要使用,因为自动装箱和卸箱是要耗费资源的。

<!--[if !supportEmptyParas]--> <!--[endif]-->

Enum Type

声明枚举类型:

Public enum Rank {one,two,three};

然后声明变量:

Private Rank rank;

枚举类型静态方法:values();返回该类型值的数据。如:Rank.values();

另一种具有方法的Enum类

Public enum Planet{

  //必须将常量声明置于最前面。

    EARTH (32.44,56.55){dosomething(){do some thing specific for earth;}},//为Planet类型的一个值。多个值用","分隔                                                                     

    VENUS (44.32,23.17){dosomething(){}};//声明值完成后以";"结束声明。

   

    Private Double mass;

    Private Double radius;

<!--[if !supportEmptyParas]--> <!--[endif]-->

    Planet(Double mass,Double radius){

        this.mass = mass;

        this.radius = radius;

    }

<!--[if !supportEmptyParas]--> <!--[endif]-->

    Public mass(){return mass);

    Public radius(){return radius);

   

    Public void doOtherThing(){

        switch (this){  //不同的枚举常量对同一种方法可以有不同的动作。

            case EARTH:doEarthThing;

            case VENUS:doVenusThing;

        }

        throw new AssertionError("Planet枚举类型没有此常量" + this);//必须要有此句

       //以后新增常量需要在swith语句中补上。为避免此种情况也可以定义一个抽象的方法,然后在每个常量中覆写此方法。  

    }

    abstract void dosomething(){do some thing}

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

<!--[if !supportEmptyParas]--> <!--[endif]-->

使用形式:EARTH.mass(已经import Planet或在同一个package)

<!--[if !supportEmptyParas]--> <!--[endif]-->

EnumSet,EnumMap
java.util 中增加两个类用于枚举类型。

EnumSet中的每一个元素都必须是同一种枚举类型。

enum.values()提供了遍历全部枚举值的途径。如果只想遍历某个范围的枚举值,可以使用EnumSet.rang(Planet.EARTH,Planet.VENUS);