(一)集合输出 (看到集合输出想Iterator)
1 Iterator迭代输出
(1)在jdk1.5之前Collection接口里面就定义有iterator()方法,通过此方法可以取得Iterator接口的实例化对象,在jdk1.5之后将此方法提升到了Iterable
接口中的方法。但是不管如何提升,必须清楚只要Collection接口有这个方法,那么set,list接口也一定有此方法。
Iterator接口最初的设计里面实际上有三个抽象方法(掌握):
判断是否有下一个元素:public boolean hasNext();
取得当前元素:public E next();
删除元素:public default void remove();
示例:标准Iterator的使用
public class Test {
public static void main(String[] args) {
List<String> all=new ArrayList<>();
all.add("hellow");
all.add("hellow");
all.add("world");
Iterator<String> iter=all.iterator();//实例化Iterator接口对象
while(iter.hasNext())
{
String str=iter.next();
System.out.println(str);
}
}
}
结果:hellow
hellow
world
注意:list接口允许重复
(2)Iterator输出的特点:只能由前向后进行内容的迭代处理,
ListIterator是Iterator的子接口,是双向迭代接口。
2 Enumeration枚举输出
Enumeration输出接口中的方法(掌握):public boolean hasMoreElements()//判断是否有下一个元素。
public E nextElement()//取得元素
但是,想要取得这个接口的实例化对象,是不可能依靠Collection,List,Set等接口。只能够依靠Vector子类,因为在Vector类中有提供一个取得Enumeration对象的方法。
即 public Enumeration <E> elements()//取得Enumeration接口对象
范例:Enumeration输出
public class Test {
public static void main(String[] args) {
Vector<String> all=new Vector<>();
all.add("hellow");
all.add("hellow");
all.add("world");
Enumeration<String> enu=all.elements();//取得Enumeration接口对象
while(enu.hasMoreElements())
{
System.out.println(enu.nextElement());//取得元素
}
}
}
结果:hellow
hellow
world
3 foreach输出
阅读排行
- Java面试题全集(上) (1102923 )
- Wi-Fi 爆重大安全漏洞,Android、iOS、Windows 等所有无线设备都不安全了 (422517 )
- Jquery 使用Ajax获取后台返回的Json数据后,页面处理 (268456 )
- Java面试题全集(中) (236886 )
- 一个非常有用的函数——COALESCE (222871 )
- Java面试题全集(下) (220855 )
- Uncaught SyntaxError: Unexpected token ) (213370 )
- 如何用adb连接android手机?(我的亲自经历)------ 顺便说说unable to connect to 192.168.1.100:5555的原因和解决方法 (210591 )
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制) (207454 )
- yum提示Another app is currently holding the yum lock; waiting for it to exit... (205658 )