historical collection classes(jdk1.1 之前)
提供的容器有arrays,vector,stack,hashtable,properties,bitset。其中定义出一种走访群集内各元素的标准方式,称为enumeration(列举器)接口,用法如下:
vector v=new vector();

for (enumeration enum =v.elements(); enum.hasmoreelements();)
{
object o = enum.nextelement();
processobject(o);
}
而在jdk1.2版本中引入了iterator接口,新版本的集合对象 (hashset,hashmap,weakheahmap,arraylist,treeset,treemap, linkedlist)是通过iterator接口访问集合元素的。
例如:
list list=new arraylist();
for(iterator it=list.iterator();it.hasnext();)


{
system.out.println(it.next());
}
/**//*
*@author 我为j狂 建立日期 2007-4-18
*
*/
package net.blogjava.lzqdiy;

import java.util.arraylist;
import java.util.enumeration;
import java.util.iterator;
import java.util.list;

public class newenumeration implements enumeration


{

iterator it;
public newenumeration(iterator it)

{
this.it=it;
// todo auto-generated constructor stub
}

public boolean hasmoreelements()

{
// todo auto-generated method stub
return it.hasnext();
}

public object nextelement()

{
// todo auto-generated method stub
return it.next();
}
public static void main(string[] args)

{
list list=new arraylist();
list.add("a");
list.add("b");
list.add("c");
for(enumeration e=new newenumeration(list.iterator());e.hasmoreelements();)

{
system.out.println(e.nextelement());
}
}
}
newenumeration是一个适配器类,通过它实现了从iterator接口到enumeration接口的适配,这样我们就可以使用老版本的代码来使用新的集合对象了。
提供的容器有arrays,vector,stack,hashtable,properties,bitset。其中定义出一种走访群集内各元素的标准方式,称为enumeration(列举器)接口,用法如下:
例如:
这样,如果将老版本的程序运行在新的java编译器上就会出错。因为list接口中已经没有elements(),而只有iterator()了。那么如何可以使老版本的程序运行在新的java编译器上呢?如果不加修改,是肯定不行的,但是修改要遵循“开-闭”原则。
这时候我想到了java设计模式中的适配器模式。
闽公网安备 35060202000074号