List和Set中Iterator的next()用法的区别

本文详细解析了Java中Iterator的hasNext()和next()方法在List和Set对象中的应用,提供了实例代码演示如何遍历Vector、ArrayList、LinkedList、HashSet等集合元素,并深入分析了两者返回值的不同之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.hasNext()函数的API解释
boolean java.util.Iterator.hasNext()
hasNext
boolean hasNext()Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.) 
Returns: 
true if the iteration has more elements
--------------------------简单的分割线-------------------------------
2.next()函数的API解释
Object java.util.Iterator.next()
next
E next()Returns the next element in the iteration. 
Returns: 
the next element in the iteration 
Throws: 
NoSuchElementException - if the iteration has no more elements
--------------------------简单的分割线-------------------------------
1.List对象中next()的使用
使用Collection类的Iterator,可以方便的遍历Vector, ArrayList, LinkedList等集合元素,避免通过get()方法遍历时,针对每一种对象单独进行编码。
示例:
Java code ?
1
2
3
4
5
6
7
8
9
10
Collection coll =  new  Vector();  //LinkedList(); //ArrayList();   
coll.add( "Tody" );   
coll.add( "is" );   
coll.add( "Sunday." );   
   
// Output all elements by iterator   
Iterator it = coll.iterator();   
while (it.hasNext()) {   
     System.out.print(it.next() +  " " );   
}  

输出:
Tody is Sunday. 

2. Set中next()的使用
Java code ?
1
2
3
4
5
6
7
8
9
10
Collection coll =  new  HashSet();   
coll.add( "Tody" );   
coll.add( "is" );   
coll.add( "Sunday." );   
   
// Output all elements by iterator   
Iterator it = coll.iterator();   
while (it.hasNext()) {   
     System.out.print(it.next() +  " " );   

输出:
is Sunday. Tody 

由上面两个例子看出,在List和Set对象中,Iterator的next()方法返回的值是不一样的。在List对象中,第一次next()返回的是第一个元素,在Set中,第一次返回的是下一个元素,但Set中,在set的结尾执行hasNext()时,返回true,表示第一个元素,执行next()会把第一个元素返回。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值