访问数组所有元素:
1.for循环经常用来遍历数组,因为通过计数器可以根据索引来访问数组的每个元素(通过索引访问每一个数组元素):
int[] ns = { 1, 4, 9, 16, 25 };
for (int i=0; i<ns.length; i++) {
System.out.println(ns[i]);
}
2.另一种for each循环,它可以更简单地遍历数组(直接访问每一个数组元素):
public class Main {
public static void main(String[] args) {
int[] ns = { 1, 4, 9, 16, 25 };
for (int n : ns) {
System.out.println(n);
}
}
}
注意:方法2也用于遍历所有“可迭代”的数据类型,如List、Map等
Java标准库提供Arrays.toString(),可用于快速打印数组内容:
import java.util.Arrays;
public class Main{
public static void main(String[] args){
int[] ns = {1, 1, 1, 1, 1, 1};
System.out.println(Arrays.toString(ns));
}
}
结果:[1, 1, 1, 1, 1, 1]
Java标准库提供Arrays.sort()排序功能:
import java.util.Arrays;
public class Main{
public static void main(String[] args){
int[] ns = {1, 9, 8, 4, 7, 3};
Arrays.sort(ns);
System.out.println(Arrays.toString(ns));
}
}
注意:调用排序函数时,有如下区别:
1. 对于整型数组,实际是修改了数组各元素值
2. 对于字符串数组,原串在内存中的位置不变,发生变化的是数组元素的指向位置