java数组
数组的使用
普通的for循环
public class Demo03 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
//打印数组元素
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i]);
}
System.out.println("=============");
//计算所有元素的和
int sum = 0;
for (int i = 0; i < arrays.length; i++) {
sum = sum + arrays[i];
}
System.out.println("sum="+sum);
System.out.println("==============");
//查找最大元素
int max = arrays[0];
for (int i = 0; i < arrays.length; i++) {
if (arrays[i] > max){
max = arrays[i];
}
}
System.out.println("max="+max);
}
}
for-each循环
public class Demo04 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
//jdk1.5 没有下标
for (int array : arrays) {
System.out.println(array);
}
}
}
1
2
3
4
5
数组作方法入参
public class Demo04 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
printArray(arrays);
}
//打印数组元素
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.print(arrays[i]+" ");
}
}
}
1 2 3 4 5
数组作返回值
public class Demo04 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
int[] reverse = reverse(arrays);
printArray(reverse);
}
//打印数组元素
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.print(arrays[i]+" ");
}
}
//反转数组
public static int[] reverse(int[] arrays){
int[] result = new int[arrays.length];
for (int i = 0,j=arrays.length-1; i <arrays.length ; i++,j--) {
//result[] = arrays[i]
result[j] = arrays[i];
}
return result;
}
}
多维数组
多维数组可以看成是数组的数组,比如二维数组就是一个特殊的一维数组,其每一个元素都是一个一维数组。
二维数组
int a[][] = new int[2][5];
public class Demo05 {
public static void main(String[] args) {
int[][] array = {{1,2},{2,3},{3,4},{4,5}};
printArray(array[0]);
System.out.println(array[2][0]);
System.out.println(array[2][1]);
}
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.print(arrays[i]+" ");
}
}
}
1 2
3
4
ublic class Demo05 {
public static void main(String[] args) {
int[][] array = {{1,2},{2,3},{3,4},{4,5}};
System.out.println(array.length);
System.out.println(array[0].length);
}
4(外面有4个)
2(里面有两个)
全部循环出来
public class Demo05 {标签:26,java,arrays,System,笔记,int,static,public,out From: https://www.cnblogs.com/12345ssdlh/p/16719030.html
public static void main(String[] args) {
int[][] array = {{1,2},{2,3},{3,4},{4,5}};
for (int i = 0; i <array.length ; i++) {
for (int j = 0; j <array[i].length ; j++) {
System.out.println(array[i][j]);
}
}
}
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.print(arrays[i]+" ");
}
}
}
1
2
2
3
3
4
4
5