java5新特性

(一)泛型

1.通俗的讲,Java的泛型就是创建一个用类型作为参数的类,如下:

1)List<Integer> list = new ArrayList<Integer>(); ------ 泛型

        list.add(new Integer(10));                

        Integer a = list.get(0);   

2)Map<String,Integer> m = new HashMap<String,Integer>();
         m.put("a",1);                 ------ 自动封装机制
         m.put("b",2);
         m.put("c",3);
         int b = m.get("b");         ------ 自动解封机制

2.自定义泛型类

class A<G>
{
//定义属性
G a;
//定义构造函数
A(G a){
       this.a = a;
}
void print(){
       System.out.println(a);
}

public static void main(String[] args)
{
       A<String> a1 = new A<String>("a1");
       a1.print();
       A<Integer> a2 = new A<Integer>(1);
       a2.print();
}
}

3)用extends和super来控制泛型的类型范围

class A <B extends List>{ };
表示B只能是List的子类或子接口A<String> a= new A<String>();就是错误的。
如果用super的话就是表示父类或者父接口了。

4)循环

void print(List<Integer> a) {
         for (Integer i : a) {      ------ 表示从a中不断的取出对象定义成 i 然后进行循环
             System.out.println(i);
         }
}

void print(List<?> a) {     ------ 类型通配符,用?表示不知道List里放的什么类型
         for (Integer i : a) {
             System.out.println(i);
         }
}

(二) 可变参数(Vararg)

public class program {

     static void test(int... ints){
       for (int i = 0; i < ints.length; i++){
         System.out.println(ints[i]);
       }
     }
  
     public static void main(String[] args) {
       test(10, 20, 30, 40, 50);
     }
}

(三) 枚举(Enum)

public class program {

  enum Color {
       Red,
       White,
       Yellow
     }
  
     public static void main(String[] args) {
    Color[] cs = Color.values();
       for(Color c : cs){
         System.out.println(c);
       }
     }
}

(四) 静态导入(Static Import)

使用静态导入可以使被导入类的所有静态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名。

import static java.lang.Math.*;

public class program {

     public static void main(String[] args) {
       int i = (int)(random()*10);
       System.out.println(i);
     }
}

(五) 格式化输入输出

public class program {

     public static void main(String[] args) {
    System.out.printf("Integer=%d String=%s", 13, "abc");
     }
}

格式化的格式是 "%[argument_index$][flags][width][.precision]conversion"。

(六) 标注(Annotation)

标注(Annotation)就是在程序中加上一些说明,容器在调用这些类,方法的时候就知道怎么处理了。

例如下面是在seasar框架中使用的例子
@StrutsActionForm(name = "ownerForm")    //can replace the struts config file
public class OwnerForm{}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值