java 5 新特性 for_Java 5 新特性

1、泛型(Generic Types)

泛型就像是C++的模板,缘由的Collection API加上泛型支持后,增加对类型的检查,减少程序错误的机会。

1 //JDK 1.4

2 Map map = new HashMap(); //未对类型作限制,可能导致运行时出错

3 map.put(1, "1111");4 map.put("2", "2222");5

6 //JDK 1.5

7 Map map = new HashMap(); //对类型作限制,编译时即检查

8 map.put(1, "1111"); //编译出错

9 map.put(“2”, "2222");

2、foreach循环(Enhanced for Loop)

foreach循环,有时也称forin循环,在许多编程语言(C#,Ruby, JavaScript)中都有出现,可以直接将一个Array或Map展开,而不必由程序员自行检查边界,勊有有效减少错误机会。

1 String[] array = {"ABC", "DEF"};2 for(String item : array) {3 System.out.println(item);4 }

3、自动装箱/拆箱(Auto-Boxing/Unboxing)

1 //没有自动装箱/拆箱

2 Integer count = new Integer(20);3

4 //有自动装箱/拆箱功能

5 Integer x = 20;6 Integer y = 20;7 System.out.println(x == y); //true, 当数值位于-128~127范围时,Integer采用享元模式

8 x = 128;9 y = 128;10 System.out.println(x == y); //false

11 System.out.println(y + x); //256

4、枚举类型(Typesafe Enums)

过去Java认为enum的关键字是不必要的功能,因为用public static final int就可以取代enum,因此过去一直不用。J2SE 5.0中的class如果是enum,在class file中会被粘贴一个ACC_ENUM标签。

1 //JDK 1.4

2 public classJavaTech {3 public static final int J2ME = 1;4 public static final int J2SE = 2;5 public static final int J2EE = 3;6 }7

8 //JDK 1.5

9 public enumJavaTech {10 J2ME, J2SE, J2EE11 }

5、可变长度参数(Varargs)

1 private voidprint(String... args) {2 for(String arg : args) {3 System.out.println(arg);4 }5 }6

7 print("AAA");8 print("AAA", "BB");9 print("AAA", "BB", "CCC");

6、静态引入(static import)

这个特性允许程序员将一个类型中的静态内容引入到当前程序中。

1 import staticjava.lang.System.out;2

3 public classMain {4

5 public static voidmain(String[] args) {6 out.println("Hello World!");7 }8

9 }

7、注解(Annotation)

Annotation全名是Program Annotation Facility, 类似与.NET的属性(Attribute)。Java的注解是一种接口,继承自java.lang.annotation.Annotation。Class File则粘贴ACC_ANNOTATION标签。

从5.0开始,javadoc的@deprecated(代表不建议使用的方法或类型)也被Annotation中的@Deprecated取代。

1 @SuppressWarnings("deprecation")2 public voidtestAnnotation() {3 System.runFinalizersOnExit(true);4 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值