1 for循环遍历
通常遍历数组都是使用for循环来实现。遍历一维数组很简单,遍历二维数组需要使用双层for循环,通过数组的length属性可获得数组的长度。
程序示例:
- 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语句遍历
在遍历数组时,使用foreach语句更简单。
程序示例:
- 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 Arrays工具类中toString静态方法遍历
利用Arrays工具类中的toString静态方法可以将一维数组转化为字符串形式并输出。
程序示例:
- 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]));//将一维数组转化为字符串输出
- }
- }
- }