文章摘自:
https://www.liaoxuefeng.com/wiki/1252599548343744/1259543088592672
1.遍历数组的三种方式:
public class Main { public static void main(String[] args) { int[] ns = { 1, 4, 9, 16, 25 }; for (int i=0; i<ns.length; i++) { int n = ns[i]; System.out.println(n); } } }
public class Main { public static void main(String[] args) { int[] ns = { 1, 4, 9, 16, 25 }; for (int n : ns) { System.out.println(n); } } }
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] ns = { 1, 1, 2, 3, 5, 8 }; System.out.println(Arrays.toString(ns)); } }
2.数组的排序
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 }; Arrays.sort(ns); System.out.println(Arrays.toString(ns)); } }
对数组的排序实际上修改了数组本身。
3.二维数组
public class Main { public static void main(String[] args) { int[][] ns = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int[] arr0 = ns[0]; System.out.println(arr0.length); // 4 } }
二维数组的每个数组元素的长度并不要求相同,例如,可以这么定义ns
数组:
int[][] ns = { { 1, 2, 3, 4 }, { 5, 6 }, { 7, 8, 9 } };
遍历二维数组:
for (int[] arr : ns) { for (int n : arr) { System.out.print(n); System.out.print(', '); } System.out.println(); }
import java.util.Arrays; public class Main { public static void main(String[] args) { int[][] ns = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; System.out.println(Arrays.deepToString(ns)); } }