编程资料集中营
 | 网站首页 | 文章中心 | 编程资料2 | 软件下载 | BT下载 | 八卦星闻 | 音乐在线 | 在线游戏 | 免费电影 | 给我留言 | 
          ★★★
【字体:
进入问吧

本站地址:http://www.bajiao123.com

作者:admin    文章来源:网络    点击数:    更新时间:2006-12-27    

JDK5.0的11个主要新特征-Java技术

     Integer i = 100;
              System.out.println(t.getString(s));
              System.out.println(t.getString(i));
              }
}1.3 受限泛型

  受限泛型是指类型参数的取值范围是受到限制的. extends关键字不仅仅可以用来声明类的继承关系, 也可以用来声明类型参数(type parameter)的受限关系.例如, 我们只需要一个存放数字的列表, 包括整数(Long, Integer, Short), 实数(Double, Float), 不能用来存放其他类型, 例如字符串(String), 也就是说, 要把类型参数T的取值泛型限制在Number极其子类中.在这种情况下, 我们就可以使用extends关键字把类型参数(type parameter)限制为数字

  示例

public class Limited<T extends Number> {

       public static void main(String[] args) {
              Limited<Integer> number;   //正确
              Limited<String> str;       //编译错误
       }
}

  1.4  泛型与异常

  类型参数在catch块中不允许出现,但是能用在方法的throws之后。例:

import java.io.*;

interface Executor<E extends Exception> {
       void execute() throws E;
}

public class GenericExceptionTest {
       public static void main(String args[]) {
              try {
                     Executor<IOException> e = new Executor<IOException>() {
                            public void execute() throws IOException{
                                   // code here that may throw an
                                   // IOException or a subtype of
                                   // IOException
                            }
                            };
                     e.execute();
              } catch(IOException ioe) {
                     System.out.println("IOException: " + ioe);
                     ioe.printStackTrace();
              }
       }
}

  1.5 泛型的通配符"?"

  "?"可以用来代替任何类型, 例如使用通配符来实现print方法。

public static void print(GenList<?> list) {})


  1.6  泛型的一些局限型

  不能实例化泛型

T t = new T(); //error


  不能实例化泛型类型的数组

T[] ts= new T[10];   //编译错误


  不能实例化泛型参数数

Pair<String>[] table = new Pair<String>(10); // ERROR


  类的静态变量不能声明为类型参数类型

public class GenClass<T> {

     private static T t;    //编译错误
}

  泛型类不能继承自Throwable以及其子类

public GenExpection<T> extends Exception{}    //编译错误


  不能用于基础类型int等

Pair<double> //error

Pair<Double> //right

2 增强循环(Enhanced for Loop)

  旧的循环

Linke

上一页  [1] [2] [3] [4] [5] [6] [7] [8] 下一页

   

进入问吧

本站地址:http://www.bajiao123.com

文章录入:admin    责任编辑:admin 
高级搜索
编程资料集中营