Friday, 15 August 2014

Arrays utility class and it's method (sort, copyof, fill, equals)

Arrays utility class is provided in java.util package. It provides some utility methods to performs more operation with arrays like copy an array into another one, sorting, filling and to check arrays are equals or not etc.

Some important methods are used bellow:

public static void main(String[] args) {
String strArr[]={"one","two","three","four"};
System.out.println("First array.");
printMe(strArr);
   
//Search element in the array
int isFound=Arrays.binarySearch(strArr, "one");
   System.out.println("contains : "+isFound);
   
//Copy an array into another array
   String [] sArr1=Arrays.copyOf(strArr,6);
   sArr1[4]="five";
   sArr1[5]="six";
   System.out.println("Second array.");
   printMe(sArr1);
 
//Copy from index to index.
   String [] sArr2=Arrays.copyOfRange(strArr, 2, strArr.length);
   System.out.println("Third array.");
   printMe(sArr2);
 
//replace all element of an array with same value.  
   Integer []intArr={1,2,3,4,5};
   Arrays.fill(intArr, 1);
   printMe(intArr);
  Integer []intArr1={1,2,3,4,5};
  Integer []intArr2={1,2,3,4,5};
 
  //check both arrays are equal.
  boolean isEqual=Arrays.equals(intArr1, intArr2);
  System.out.println(isEqual);
 
  //if both are equal than hashCode should be equal.
  if(Arrays.hashCode(intArr1)==Arrays.hashCode(intArr2))
  System.out.println("Both arrays hashCode are equal.\n");
  else
  System.out.println("Both arrays hashCode are not equal.\n");
  //sort an array.
  System.out.println("Unsorted array");
  printMe(strArr);
  Arrays.sort(strArr);
  System.out.println("Sorted array");
  printMe(strArr);

//convert an array into list.
  List<String> ll=Arrays.asList(strArr);
  System.out.println(ll);
}

/* Generic method to print array */
public static <T> void printMe(T []arr){
for(T s:arr){
    System.out.print(s+", ");
}
System.out.println("\n");
}

Output:



No comments:

Post a Comment