1 package day1_5; 2 3 import java.util.Arrays; 4 5 public class ArraysUtil { 6 //遍历数组 7 public void print(int[] arr) { 8 for (int i : arr) { 9 System.out.print(i + " "); 10 } 11 System.out.println(); 12 } 13 14 //复制数组 15 public int[] copy(int[] arr) { 16 int[] newArr = new int[arr.length]; 17 for (int i = 0; i < arr.length; i++) { 18 newArr[i] = arr[i]; 19 } 20 return newArr; 21 } 22 23 //最大值 24 public int getMax(int[] arr) { 25 int maxValue = arr[0]; 26 for (int i = 0; i < arr.length; i++) { 27 if (arr[i] > maxValue) { 28 maxValue = arr[i]; 29 } 30 } 31 return maxValue; 32 } 33 34 //最小值 35 public int getMin(int[] arr){ 36 int minValue = arr[0]; 37 for (int i = 0; i < arr.length; i++) { 38 if (arr[i] < minValue) { 39 minValue = arr[i]; 40 } 41 } 42 return minValue; 43 } 44 45 //求和 46 public int getSum(int[] arr){ 47 int sumValue = 0; 48 for (int i = 0; i < arr.length; i++) { 49 sumValue += arr[i]; 50 } 51 return sumValue; 52 } 53 54 //平均值 55 public int getAvg(int[] arr){ 56 return getSum(arr)/arr.length; 57 } 58 59 60 //查找元素 61 public int getIndex(int[] arr,int target){ 62 //线性查找 63 for (int i=0; i < arr.length; i++) { 64 if (arr[i] == target) { 65 return i; 66 } 67 } 68 return -1;//负数表示数组中没有目标元素 69 } 70 71 //反转数组 72 public void reverse(int[] arr){ 73 for (int i = 0,j = arr.length-1; i < j; i++,j--) { 74 int tmp = arr[i]; 75 arr[i] = arr[j]; 76 arr[j] = tmp; 77 } 78 } 79 80 //冒泡排序 81 public void sort(int[] arr){ 82 for (int i = 0; i < arr.length-1; i++) { 83 for (int j = 0; j < arr.length-i-1; j++) { 84 int tmp; 85 if (arr[j] > arr[j + 1]) { 86 tmp = arr[j]; 87 arr[j] = arr[j+1]; 88 arr[j+1] = tmp; 89 } 90 } 91 } 92 } 93 94 }
测试类
1 package day1_5; 2 3 4 import java.util.Arrays; 5 6 public class ArrayUtilTest { 7 public static void main(String[] args) { 8 int[] arr = new int[]{12,46,-12,90,-46,0,4,-90,89}; 9 ArraysUtil arraysUtil = new ArraysUtil(); 10 System.out.println("----遍历数组----"); 11 arraysUtil.print(arr); 12 System.out.println("----复制数组----"); 13 int[] arr2 = arraysUtil.copy(arr); 14 System.out.println(Arrays.toString(arr2)); 15 System.out.println("----最大值----"); 16 int max = arraysUtil.getMax(arr); 17 System.out.println(max); 18 System.out.println("----最小值----"); 19 int min = arraysUtil.getMin(arr); 20 System.out.println(min); 21 System.out.println("----求和----"); 22 int sum = arraysUtil.getSum(arr); 23 System.out.println(sum); 24 System.out.println("----平均值----"); 25 int ave = arraysUtil.getAvg(arr); 26 System.out.println(ave); 27 System.out.println("----查找元素----"); 28 int index = arraysUtil.getIndex(arr, -12); 29 System.out.println(index); 30 System.out.println("----反转数组----"); 31 arraysUtil.reverse(arr); 32 System.out.println(Arrays.toString(arr)); 33 System.out.println("----冒泡排序----"); 34 arraysUtil.sort(arr); 35 System.out.println(Arrays.toString(arr)); 36 37 } 38 }
打印结果