j2se 5.0引入了许多新型的集合api-你需要了解它们以便能够正确地实现泛型定制的集合-它可以无缝地与多种类型和新型的"for each"结构一起工作。本文将向你展示示怎样创建与j2se最新特征相兼容的集合。
一、 创建支持泛型的类
首先,你必须学习如何创建一个允许存在"泛型类型"的类。这意味着无论何时实例化你的类,你都能够指定一个或多个java类型与该类相关联。为了说明这个问题,请考虑列表1中的一个简单示例类。
注意,列表1中的类是如何声明的。它在尖括号之间指定三个泛型。这些泛型是真实类型的占位符。当你声明一个这种类型的类时,你可以指定一个类来代替one,two和three。如果你不这样做,那么该类将使用object的默认类型。
这个类显示出怎样设计一个类来接收三个泛型类型。当你创建一个这种类型的类时你要支持准确的类型。
列表1.泛型类:
| package com.heatonresearch.examples.collections; public class example<one, two, three> { private one one; private two two; private three three; public one getone() { return one; } public void setone(one one) { this.one = one; } public three getthree() { return three; } public void setthree(three three) { this.three = three; } public two gettwo() { return two; } public void settwo(two two) { this.two = two; } public static void main(string args[]) { example<double, integer, string> example = new example<double, integer, string>(); example.setone(1.5); example.settwo(2); example.setthree("three"); } } |
| example example=new example(); |
| example.setone(1.5); example.settwo(2); example.setthree("three"); |
| package com.heatonresearch.examples.collections; import java.util.*; public class queue { private arraylist list = new arraylist(); public void push(t obj) { list.add(obj); } public t pop() throws queueexception { if (size() == 0) throw new queueexception( "tried to pop something from the queue, " + "when it was empty"); t result = list.get(0); list.remove(0); return result; } public boolean isempty() { return list.isempty(); } public int size() { return list.size(); } public void clear() { list.clear(); } } |
| public class queue |
| package com.heatonresearch.examples.collections; public class queueexception extends exception { public queueexception(string msg) { super(msg); } } |
| if (size() == 0) throw new queueexception("tried to pop something from the queue, " + "when it was empty"); |
| t result = list.get(0); list.remove(0); return result; |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器