Home  >  Article  >  Java  >  How to use java foreach

How to use java foreach

(*-*)浩
(*-*)浩Original
2019-05-22 13:12:2624112browse

The foreach statement is one of the new features of java5. Foreach provides developers with great convenience in traversing arrays and collections.

How to use java foreach

The foreach statement is a special simplified version of the for statement, but the foreach statement cannot completely replace the for statement. However, any foreach statement can be rewritten as a for statement version.

foreach is not a keyword. It is customary to call this special for statement format a "foreach" statement. Understanding foreach literally means "for each" in English. This is actually what it means.

Foreach statement format:

for(元素类型t 元素变量x : 遍历对象obj){
     引用了x的java语句;
}

Example: foreach usage.

//下面通过两个例子简单例子看看foreach是如何简化编程的。代码如下:
//一、foreach简化数组和集合的遍历
import java.util.Arrays; 
import java.util.List; 
import java.util.ArrayList; 
 
public class TestArray { 
	public static void main(String args[]) { 
		TestArray test = new TestArray(); 
		test.test1(); 
		test.listToArray(); 
		test.testArray3(); 
	} 
 
	/** 
	* foreach语句输出一维数组 
	*/ 
	public void test1() { 
		//定义并初始化一个数组 
		int arr[] = {2, 3, 1}; 
		System.out.println("----1----排序前的一维数组" ); 
		for (int x : arr) { 
		System.out.println(x); //逐个输出数组元素的值 
		} 

		//对数组排序 
		Arrays.sort(arr); 

		//利用java新特性for each循环输出数组 
		System.out.println("----1----排序后的一维数组" ); 
		for (int x : arr) { 
			System.out.println(x); //逐个输出数组元素的值 
		} 
	} 
 
	/** 
	* 集合转换为一维数组 
	*/ 
	public void listToArray() { 
		//创建List并添加元素 
		List<String> list = new ArrayList<String>(); 
		list.add("1" ); 
		list.add("3" ); 
		list.add("4" ); 
		 
		//利用froeach语句输出集合元素 
		System.out.println("----2----froeach语句输出集合元素" ); 
		for (String x : list) { 
			System.out.println(x); 
		} 
		 
		//将ArrayList转换为数组 
		Object s[] = list.toArray(); 
		 
		//利用froeach语句输出集合元素 
		System.out.println("----2----froeach语句输出集合转换而来的数组元素" ); 
		for (Object x : s) { 
			System.out.println(x.toString()); //逐个输出数组元素的值 
		} 
	} 
	/** 
	* foreach输出二维数组测试 
	*/ 
	public void testArray2() { 
		int arr2[][] = {{4, 3}, {1, 2}}; 
		System.out.println("----3----foreach输出二维数组测试" ); 
		for (int x[] : arr2) { 
		for (int e : x) { 
			System.out.println(e); //逐个输出数组元素的值 
		} 
	} 
}

Result:

----1----排序前的一维数组
2
3
1
----1----排序后的一维数组
1
2
3
----2----froeach语句输出集合元素
1
3
4
----2----froeach语句输出集合转换而来的数组元素
1
3
4

Related learning recommendations: java basic tutorial

The above is the detailed content of How to use java foreach. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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