Java:遍历数组的三种方法

1、for循环遍历数组 用for循环遍历数组是很常见的一种方法,Java语言中通过数组的length属性可获得数组的长度。

package demo;

public class test {
          
   
	public static void main(String[] args) {
          
   
		int [] array = {
          
   1,2,3,4,5};
		for(int i = 0;i < array.length;i++) {
          
   
			System.out.print(array[i] + " ");
		}
	}
}

2、基于循环语句的遍历 JDK1.5对for语句的功能给予扩充、增强,以便于更好的遍历数组; 语法格式:

for(声明循环变量:数组的名字){
          
   //注意:这里的“声明循环变量”一定是声明变量,不可以使用已经被声明的变量
	....
}

例子:

package demo;

public class test {
          
   
	public static void main(String[] args) {
          
   
		int [] array = {
          
   1,2,3,4,5};
		for(int in:array) {
          
   
			System.out.print(in + " ");
		}
	}
}

3、使用toString()方法遍历数组 这种方法是JDK1.5提供的一个简单的输出数组元素的值的方法。使用Arrays类调用public static String toString(int[] a)方法可以得到指定的一维数组a的如下格式的字符串表示。 [a[0],a[1]…a[a.lenth-1]]

package demo;

import java.util.Arrays;

public class test {
          
   
	public static void main(String[] args) {
          
   
		int [] array = {
          
   1,2,3,4,5};
		System.out.print(Arrays.toString(array));
	}
}
经验分享 程序员 微信小程序 职场和发展