论坛首页 入门技术论坛

corejava辅导(16--1)

浏览 1079 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-12-03  

Java5.0的新特性

 

自动装箱和自动拆箱

 

自动封箱和自动拆箱,它实现了简单类型和封装类型的相互转化时,实现了自动转化。

 

自动封箱解箱只在必要的时候才进行。还有其它选择就用其它的

byte b     -128~127

Byte b     多一个null

 

简单类型和封装类型之间的差别

封装类可以等于null  ,避免数字得0时的二义性。

Integer i=null

int ii=i  会抛出NullException 异常)

相当于 int ii=i.intValue();

Integer i=1;相当于Integer i=new Integer(1);

 

在基本数据类型和封装类之间的自动转换

5.0之前

Integer i=new Integer4);

int  ii= i.intValue();

 

5.0之后

Integer i=4

Long l=4.3;

 

静态引入

 

静态成员的使用,使用import static 引入静态成员,也就是可以用静态引入是导入包中的某个类的静态成员,在使用时不用再写类名。

很简单的东西,看一个例子:

 

没有写静态引入

 

public class Test{

public static void main(String[] args){

Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));

}

}

 

写了静态引入

import static java.lang.Math.*;

public class Test{

public static void main(String[] args){

System.out.println(sqrt(pow(x, 2) + pow(y, 2)));

}

}

其中import static java.lang.Math.*;就是静态导入的语法,它的意思是导入Math类中的所有static方法和属性。这样我们在使用这些方法和属性时就不必写类名。

 

需要注意的是默认包无法用静态导入,另外如果导入的类中有重复的方法和属性则需要写出类名,否则编译时无法通过。

 

增强的for循环

 

for-each循环实现了对数组和集合的便利的统一,解决遍历数组和遍历集合的不统一。

 

import java.util.*;

import java.util.Collection;

 

public class Foreach

{

private Collection<String> c = null;

    private String[] belle = new String[4];

    public Foreach()

    {

        belle[0] = "西施";

             belle[1] = "王昭君";

             belle[2] = "貂禅";

             belle[3] = "杨贵妃";

             c = Arrays.asList(belle);

    }

    public void testCollection(){

        for (String b : c){

              System.out.println("曾经的风化绝代:" + b);

        }

    }

    public void testArray(){

        for (String b : belle){

              System.out.println("曾经的青史留名:" + b);

        }

    }

    public static void main(String[] args){

        Foreach each = new Foreach();

        each.testCollection();

        each.testArray();

    }

}

 

 

对于集合类型和数组类型的,我们都可以通过foreach语法来访问它。上面的例子中,以前我们要依次访问数组,挺麻烦:

 

for (int i = 0; i < belle.length; i++){

        String b = belle[i];

        System.out.println("曾经的风化绝代:" + b);

}

 

 

现在只需下面简单的语句即可:

 

for (String b : belle){

       System.out.println("曾经的青史留名:" + b);

 }

 

对集合的访问效果更明显。以前我们访问集合的代码:

for (Iterator it = c.iterator(); it.hasNext();){

        String name = (String) it.next();

        System.out.println("曾经的风化绝代:" + name);

}

 

现在我们只需下面的语句:

for (String b : c){

        System.out.println("曾经的风化绝代:" + b);

}

 

Foreach也不是万能的,它也有以下的缺点:

 

在以前的代码中,我们可以通过Iterator执行remove操作。

 

for (Iterator it = c.iterator(); it.hasNext();){

       it.remove();

}

 

但是,在现在的for-each版中,我们无法删除集合包含的对象。你也不能替换对象。

 

同时,你也不能并行的for-each多个集合。所以,在我们编写代码时,还得看情况而使用它。

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics