正 文

用J2SE 5.0创建定制的泛型集合


www.7dspace.com  更新日期:2005-11-23 8:43:57  七度空间


  三、 测试Queue类

  下列类用于测试"泛型"队列。

package com.heatonresearch.examples.collections;
 public class TestQueue {
  public static void main(String args[]) {
   Queue<Integer> queue = new Queue<Integer>();
   queue.push(1);
   queue.push(2);
   queue.push(3);
   try {
    System.out.println("Pop 1:" + queue.pop());
    System.out.println("Pop 2:" + queue.pop());
    System.out.println("Pop 3:" + queue.pop());
   }
   catch (QueueException e) { e.printStackTrace(); }
  }
 }

  前面的代码中创建的队列仅接收整型对象。

Queue<Integer> queue = new Queue<Integer>();

  接下来的测试把三个整数添加到该队列上。

queue.push(1);
queue.push(2);
queue.push(3);

  注意,添加到该队列中的这些数字都是原始的类型。因为J2SE的自动装箱特性,这些原始的int类型被自动地转变成Integer对象。

  接下来,该测试使用pop方法检索对象。在该队列为空的情况下,该测试捕获到QueueException异常。从队列中弹出三个数字的结果是:

1
2
3

  尽管在这里作为一接收的整数队列显示,但是因为泛型,所以队列类对于任何Java对象情况都能正常工作。

5页,页码:[1] [2] [3] [4] [5] 

上一篇:Foxmail 6.0 Beta1发布!加入RSS阅读器
下一篇:将自己的照片处理为苹果iPod平面广告
作者:朱先忠编译  来源:天极网 ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐