Sunday, February 15, 2015

Array Functions

We have couple of arrays functions that could be handy to perform some array operations.Listed below
- Copying array
- Copying array of a particular range
- Sorting Array
- search array


package Example1;

import java.util.Arrays;

public class CopyArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int[] array1=new int[10];
		int randomnumber;
		for(int i=0;i< array1.length;i++){
			randomnumber=(int)(Math.random()*51);
			array1[i]=randomnumber;
		}
		
		for(int row:array1){
			System.out.print(" "+row+" ");
		}
		//copy array
		System.out.println();
		int[] copyarray=Arrays.copyOf(array1, 3);
		for(int row:copyarray){
			System.out.print(" "+row+" ");
		}
		//copy array in a particular range
		System.out.println();
		int[] copyarray2=Arrays.copyOfRange(array1, 2, 6);
		for(int row:copyarray2){
			System.out.print(" "+row+" ");
		}
		
		//sort the array		
		System.out.println();
		Arrays.sort(array1);
                int exist=Arrays.binarySearch(array1, 50);
		System.out.println(exist);
		System.out.println(Arrays.toString(array1));
	}

}


output :
27 20 20 31 32 21 28 27 40 46
27 20 20
20 31 32 21
-ve value [20, 20, 21, 27, 27, 28, 31, 32, 40, 46]
>>>
------------------------------------------------------------------------------------------------------------