Java- java-util-Arrays

Java.util.Arrays

This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.

  • Arrays to list

  • Sorting & Searching

  • Copying & filling

  • public static String toString(int[] a) The string representation consists of a list of the array’s elements, enclosed in square brackets (-[]”).
    public static void main(String[] args) throws Exception {  
      String a[] = {"a", "b", "c"};
      System.out.println("OLD \t :"+a.toString());
      System.out.println("New \t :"+Arrays.toString(a));
    	}
    --------------------------------------	
    OLD 	 :[Ljava.lang.String;@6d06d69c
    New 	 :[a, b, c]
    
  • public static List asList(T… a) - This method returns a fixed-size list backed by the specified array. adding or removing elements from the list aren’t allowed on this created list, you can only read or overwrite the elements

  • public static void sort(int[] a) – Sorts the specified array into ascending numerical order.

  • public static void sort(int[] a, int fromIndex, int toIndex) If we wish to sort a specified range of the array into ascending order.

  • public static int binarySearch(int[] a, int key) Returns an int value for the index of the specified key in the specified array. Returns a negative number if the specified key is not found in the array.

  • public static int[] copyOf(int[] original, int newLength) Copies the specified array and length. It truncates the array if provided length is smaller and pads if provided.

  • public static int[] copyOfRange(int[] original, int from, int to) Copies the specified range of the specified array into a new array

  • public static void fill(int[] a, int val)Fills all elements of the specified array with the specified value.

  • public static void fill(int[] a, int fromIndex, int toIndex, int val) – Fills elements of the specified array with the specified value from the fromIndex element, but not including the toIndex element.

  • static boolean equals(Object[] a, Object[] a2) - It will compare the Content of two arrays & must be in same Order
    public static void main(String[] args) throws Exception {       
        String a[] = {"a", "b", "c"};
        String b[] = {"a", "b", "c"};
        String c[] = {"c", "b", "a"};
        System.out.println("OLD : "+a.equals(b));
        System.out.println("New : "+Arrays.equals(a, b));
        System.out.println("Wrong Order : "+Arrays.equals(a, c));
        //It will compare the Content & must be in same Order
       }  
    ------------------------   
    OLD : false
    New : true
    Wrong Order : false
    
  • static int hashCode(Object[] a)- This method returns a hash code based on the contents of the specified array.