Enumeration接口的使用
1,Enumeration(枚举)接口的作用和Iterator类似,只提供了遍历Vector和HashTable类型集合元素的功能,不支持元素的移除操作。
2,该接口有两个方法:
1)hasMoreElements() 判断集合里有没有元素 //是否还有元素,如果有返回true,否则表示至少含有一个元素
2)nextElement() 遍历集合时获取遍历的下一个元素 返回对象只能的下一个元素,否则抛出NoSuchElementException异常。
3,案例1:
public class TestEnumeration{
public static void main(String[] args){
Vector v = new Vector();
v.addElement("Lisa");
v.addElement("Billy");
v.addElement("Mr Brown");
Enumeration e = v.elements();//返回Enumeration对象
while(e.hasMoreElements()){
String value = (String)e.nextElement();//调用nextElement方法获得元素
System.out.print(value);}}}
案例2:
/**
* 获取request参数,封装到map中,并按key值排序
* @param request
* @return
*/
public static TreeMap<String, String> getParameterMap(HttpServletRequest request){
TreeMap<String, String> map = new TreeMap<String, String>();
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String param = en.nextElement();
String value = request.getParameter(param.toString());
map.put(param, value);
}
return map;
}
4,Enumeration和Iterator接口功能相似,而且Iterator的功能还比Enumeration多,那么为什么还要使用Enumeration
这是因为java的发展经历了很长时间,一些比较古老的系统或者类库中的方法还在使用Enumeration接口,因此为了兼容,还是需要使用Enumeration。
Enumeration接口是JDK1.0时推出的,是最好的迭代输出接口,最早使用Vector(现在推荐使用ArrayList)时就是使用Enumeration接口进行输出。虽然Enumeration是一个旧的类,但是在JDK1.5之后为Enumeration类进行了扩充,增加了泛型的操作应用。
1,Enumeration(枚举)接口的作用和Iterator类似,只提供了遍历Vector和HashTable类型集合元素的功能,不支持元素的移除操作。
2,该接口有两个方法:
1)hasMoreElements() 判断集合里有没有元素 //是否还有元素,如果有返回true,否则表示至少含有一个元素
2)nextElement() 遍历集合时获取遍历的下一个元素 返回对象只能的下一个元素,否则抛出NoSuchElementException异常。
3,案例1:
public class TestEnumeration{
public static void main(String[] args){
Vector v = new Vector();
v.addElement("Lisa");
v.addElement("Billy");
v.addElement("Mr Brown");
Enumeration e = v.elements();//返回Enumeration对象
while(e.hasMoreElements()){
String value = (String)e.nextElement();//调用nextElement方法获得元素
System.out.print(value);}}}
案例2:
/**
* 获取request参数,封装到map中,并按key值排序
* @param request
* @return
*/
public static TreeMap<String, String> getParameterMap(HttpServletRequest request){
TreeMap<String, String> map = new TreeMap<String, String>();
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String param = en.nextElement();
String value = request.getParameter(param.toString());
map.put(param, value);
}
return map;
}
4,Enumeration和Iterator接口功能相似,而且Iterator的功能还比Enumeration多,那么为什么还要使用Enumeration
这是因为java的发展经历了很长时间,一些比较古老的系统或者类库中的方法还在使用Enumeration接口,因此为了兼容,还是需要使用Enumeration。
Enumeration接口是JDK1.0时推出的,是最好的迭代输出接口,最早使用Vector(现在推荐使用ArrayList)时就是使用Enumeration接口进行输出。虽然Enumeration是一个旧的类,但是在JDK1.5之后为Enumeration类进行了扩充,增加了泛型的操作应用。
Enumeration接口常用的方法有hasMoreElements()(判断是否有下一个值)和 nextElement()(取出当前元素),这些方法的功能跟Iterator类似,只是Iterator中存在删除数据的方法,而此接口不存在删除操作。