1. 程式人生 > >【Java】ArrayUtils的實現

【Java】ArrayUtils的實現

public class ArrayUtils{

    //1.計算陣列中最大值
    public static int arrayMaxElement(int[] data){
		int max = data[0];
        for(int i=0; i<data.length; i++){
			if(data[i] > max){
				max = data[i];
			}
		}
        return max;
    }
    
    //2.計算陣列中最小值
    public static int arrayMinElement(int[] data){
		int min = data[0];
		for(int i=0; i<data.length; i++){
			if(data[i] < min){
				min = data[i];
			}
		}
		return min;
    }
    
    
    //3.計算陣列值之和
    public static int arrayElementSum(int[] data){
		int sum = 0;
		for(int i=0; i<data.length; i++){
			sum += data[i];
		}
		return sum;
    }
    
    //4.陣列拼接
    public static int[] arrayJoin(int[] a, int[] b){
        int[] c = new int[a.length+b.length];
		for(int i=0; i<a.length; i++){
			c[i]=a[i];
		}
		for(int i=a.length; i<c.length; i++){
			c[i]=b[i-a.length];
		}
		return c;
    }

    //5.陣列擷取
    //[start, end)
    public static int[] arraySub(int[] data, int start , int end){
        for(int i=start; i<end; i++){
			System.out.print(data[i]+" ");
		}
		System.out.print("\n");
        return null;
    }
    
    //6.陣列列印
    public static void printArray(int[] data){
        for(int i=0; i<data.length; i++){
			System.out.print(data[i]+" ");
		}
		System.out.print("\n");
    }
    
    //7.陣列反轉
    // 比如:[1,2,3,4] => [4,3,2,1]
    public static void printReversal(int[] data){
		int temp = 0;
		int left = 0;
		int right = data.length-1;
		while(left<right){
			temp = data[left];
			data[left] = data[right];
			data[right] = temp;
			left++;
			right--;
		}
		printArray(data);
    }
    
    public static void main(String[] args){
        int[] data = new int[]{1,4,9,10};  
		int[] data1 = new int[]{11,12,13,14};
		//最大值
		System.out.println(arrayMaxElement(data)); 
		
		//最小值
		System.out.println(arrayMinElement(data));
		
		//和
		System.out.println(arrayElementSum(data));
		
		//陣列拼接
		printArray(arrayJoin(data,data1));
		System.out.print("\n");
		
		//資料擷取
		arraySub(data,1,3);
		
		//列印陣列
		printArray(data);
		
		//陣列反轉
		printReversal(data);
    }
}