Home  >  Article  >  Java  >  Three ways to traverse arrays in java

Three ways to traverse arrays in java

王林
王林Original
2019-11-13 09:56:418417browse

Three ways to traverse arrays in java

1. For loop traversal

Usually traversing an array is implemented using a for loop. Traversing a one-dimensional array is very simple. Traversing a two-dimensional array requires a double-layer for loop. The length of the array can be obtained through the length property of the array.

Program example:

package captain;
 
public class ArrayDemo {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int arr[][] = new int[][]{{1},{2,3},{4,5,6}};
		
		//for循环遍历二维数组。
		for(int i = 0; i < arr.length; i++){
			for(int j = 0; j < arr[i].length; j++){
				System.out.print(arr[i][j]);
			}
			System.out.println();
		}
 
	}
 
}

2. Foreach statement traversal

When traversing an array, it is simpler to use the foreach statement.

Program example:

package captain;
 
public class ArrayDemo2 {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int arr[][] = new int[][]{{4,3},{1,5}};
		
		//foreach语句遍历二维数组。
		System.out.println("数组中的元素是:");
		for(int x[]:arr){  //外层遍历得到一维数组
			for(int e:x){  //内层遍历得到数组元素
					System.out.print(e);
			}
			System.out.println();
		}
 
	}
 
}

3. ToString static method traversal in the Arrays tool class

Use the toString static method in the Arrays tool class to traverse a The dimensional array is converted into string form and output.

Program example:

package captain;
 
import java.util.Arrays;
 
public class ArrayDemo3 {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//Arrays工具类的toString静态方法遍历二维数组。
		int arr[][] = new int[][]{{9,8},{7,6,5}};
		for(int i = 0; i < arr.length; i++){//循环得到一维数组
			System.out.println(Arrays.toString(arr[i]));//将一维数组转化为字符串输出
		}
	}
 
}

Recommended tutorial: Java tutorial

The above is the detailed content of Three ways to traverse arrays in java. 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