一.
数组最常见的一个操作就是遍历。
因为数组的每个元素都可以通过
索引
来访问,通过
for
循环就可以遍历数组。
public class M {
public static void main(String[] args) {
int[] ns = { 1,
3
,
2
, 6, 5 };
for (int i=0; i<ns.length; i++) {
int n = ns[i];
System.out.println(n);
}
}
}
运行结果:
1
3
2
6
5
第二种方式是使用for each
循环,直接迭代数组的每个元素:
public class M{
public static void main(String[] args) {
int[] ns = { 1,
3
,
2
, 6, 5 };
for (int n : ns) {
System.out.println(n);
}
}
}
运行结果:
1
3
2
6
5
二.
数组
另外
最常见的一个操作就是
排序
。
冒泡排序算法对一个数组从小到大进行排序
:
import java.util.Arrays;
public class M{
public static void main(String[] args) {
int[] ns = {
1
,
3
,
2
,
6
,
5
};
//
排序前
for (int n : ns) {
System.out.println(n);
}
for (int i = 0; i < ns.length - 1; i++) {
for (int j = 0; j < ns.length - i - 1; j++) {
if (ns[j] > ns[j+1]) {
int tmp = ns[j];
ns[j] = ns[j+1];
ns[j+1] = tmp;
}
}
}
//
排序后
for (int n : ns) {
System.out.println(n);
}
}
}
运行结果:
1
3
2
6
5
1
2
3
5
6
J
ava
内置了排序功能,使用
Arrays.sort
排序:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] ns = {
1
,
3
,
2
,6,
5
};
Arrays.sort(ns);
for (int n : ns) {
System.out.println(n);
}
}
}
运行结果:
1
2
3
5
6