数组的使用
For-Each循环,数组作方法入参,数组作返回值
package com.drumk.array; public class ArrayDemo01{ 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 += arrays[i]; } System.out.println("sum="+sum); System.out.println("======================"); //查找出最大的元素 int max = arrays[0]; for (int i = 1;i<arrays.length ;i++){ if (arrays[i]>max){ max = arrays[i]; } } Systrm.out.println("max="+max); } }
package com.drumk.array; public class ArrayDemo02{ public static void main(String[] args){ int[] arrays = {1,2,3,4,5}; //JDK1.5, 没有下标 //for (int arrays :arrays){ // System.out.println(arrays); //} //printArray(arrays); int[] reverse = reverse(arrays); printArray(reverse); } //反转数组 public static int[] reverse(int[] arrays){ int[] result = new int[arrays.length]; //反转的操作 for (int i = 0,j = result.length-1;i<arrays.length;i++,j--){ result[j] = arrays[i]; } return result; } //打印数组元素 public static void printArray(int[] arrays){ for(int i = 0;i<arrays.length;i++){ System.out.print(arrays[i]+""); } } }
多维数组
多维数组可以看成是数组的数组,比如二维数组就是一个特殊的一堆数组,其每一个元素都是一个一堆数组
二维数组
解释:以上二维数字a可以看成一个两行五列的数组
package com.drumk.array; public class ArrayDemo03{ public static void main(String[] args){ //[4][2] 面对对象 /* 1,2 arrays[0] 2,3 arrays[1] 3,4 arrays[2] 4,5 arrays[3] */ int[][] arrays = {{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.print(arrays[i][j]); } } } //打印数组元素 public static void printArray(int[] arrays){ for(int i = 0;i<arrays.length;i++){ System.out.print(arrays[i]+""); } } }
Arrays类
package com.drumk.array; import java.util.Arrays; public class ArrayDemo04{ public static void main(String[] args){ int[] a = {1,2,3,4,9090,31231,543,21,3,23}; //System.out.println(a); //打印数组元素arrays.toString //System.out.println(Arrays.toString(a)); Arrays.sort(a);//数组进行排序:升序 System.out.println(Arrays.toString(a)); Arrays.fill(a,val:0); System.out.println(Arrays.toString(a)); } public static void printArrays(int[] a){ for(int i = 0;i<a.length;i++){ if(i==0){ System.out.print("["); } if(i==a.length-1){ System.out.print(a[i]+"]"); }else{ System.out.print(a[i]+","); } } } }标签:int,DAY14,Arrays,static,数组,arrays,public From: https://blog.csdn.net/Drumk/article/details/140664142