Home > Java > javaTutorial > Four ways to traverse ArrayList collection in java

Four ways to traverse ArrayList collection in java

王林
Release: 2019-11-27 13:42:53
forward
3447 people have browsed it

Four ways to traverse ArrayList collection in java

ArrayList traversal: take out the data in the ArrayList collection

Method one: for loop

Method two: Enhanced for loop: foreach

Method 3: Iterator: Iterator

Method 4: ListIterator: Bidirectional iterator

Free video tutorial recommendations: java online tutorial

Examples are as follows:

/**
 * ArrayList遍历:取出ArrayList集合中的数据
 * ①:for循环
 * ②:增强for循环:foreach
 * ③:Iterator:迭代器
 * ④:ListIterator:双向迭代器
 */
public class Demo {
	public static void main(String[] args) {
		ArrayList list = new ArrayList();
		list.add("ArrayList");
		list.add("基于数组的集合");
		list.add(true);
		list.add('I');
		list.add("也可以保存对象");
		System.out.print("第1种方式:");
		for (int i = 0; i < list.size(); i++) {//for
			System.out.print(list.get(i) + "  ");//get():获取指定索引处的值
		}
		
		System.out.print("\n第2种方式:");
		for (Object object : list) {//foreach
			System.out.print(object + "  ");
		}
		
		System.out.print("\n第3种方式:");
		Iterator iterator = list.iterator();//Iterator:可以遍历集合的迭代器
		while(iterator.hasNext()) {//boolean hasNext():是否存在下一个元素
			System.out.print(iterator.next() + "  ");//E(Object) next():获得下一个元素的值
		}
		
		System.out.print("\n第4种方式:");
		ListIterator listIterator = list.listIterator();//ListIterator:可以遍历集合的双向迭代器
		while (listIterator.hasNext()) {//boolean hasNext():从左到右依次遍历  判断是否存在下一个元素
			System.out.print(listIterator.next() + "  ");//E(Object) next():获得下一个元素的值
		}
		
		/*while (listIterator.hasPrevious()) {
		//boolean hasPrevious():逆向 ==》从右到左依次遍历 判断是否存在前一个元素
			System.out.print(listIterator.previous()+"  ");//E(Object) previous():获得上一个元素的值
		}*/
	}
}
Copy after login

Related article tutorial recommendations: java Getting Started

The above is the detailed content of Four ways to traverse ArrayList collection in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template