List和Set中Iterator的next()用法的区别?
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()方法遍历时,针对每一种对象单独进行编码。
示例:
输出:
Tody is Sunday.
2. Set中next()的使用
输出:
is Sunday. Tody
由上面两个例子看出,在List和Set对象中,Iterator的next()方法返回的值是不一样的。在List对象中,第一次next()返回的是第一个元素,在Set中,第一次返回的是下一个元素,但Set中,在set的结尾执行hasNext()时,返回true,表示第一个元素,执行next()会把第一个元素返回。
问题:
可以按照上述理解next()?
如果不是,那该怎么理解next()?
多谢!
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()方法遍历时,针对每一种对象单独进行编码。
示例:
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()的使用
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()会把第一个元素返回。
问题:
可以按照上述理解next()?
如果不是,那该怎么理解next()?
多谢!
...全文
相关推荐
JAVA 区分集合和数组
主要介绍了JAVA如何区分集合和数组,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
for,foreach,iterator的用法和区别
for,foreach,iterator的用法和区别
Java中的Set、List、Map的用法与区别介绍
主要介绍了Java中的Set、List、Map的用法与区别,需要的朋友可以参考下
详解Java中Iterable与Iterator用法
在本文中小编给大家分享了关于Java中Iterable与Iterator的用法知识点内容,有兴趣的朋友们可以学习下。
Set用法及与List的区别
该资源通过实例说明Set、迭代器、list用法,以及Set与List的区别。


Java SE
