神刀安全网

Array class in Java

There are often times when we need to do following tasks on an array in Java.

  • Fill an array with a particular value. We usually do it with the help of a for loop.
  • Sort an array.
  • Binary search in sorted array.
  • And many more..

The Arrays class of the java.util package contains several static methods that we can use to fill, sort, search, etc in arrays. This class is a member of the Java Collections Framework and is present in java.util.arrays .

  • public static String toString(int[] a)

    The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters a comma followed by a space. Elements are converted to strings as by String.valueOf(int). Returns “null” if a is null.

    // Java program to demonstrate that we can print // array elements in a single line import java.util.Arrays;  public class Main {     public static void main(String[] args)     {         int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};                  // To print the elements in one line         System.out.println(Arrays.toString(ar));     } }

    Output:

    [4, 6, 1, 8, 3, 9, 7, 4, 2]
  • 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. we can use this. The range to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive. If fromIndex == toIndex, the range to be sorted is empty.

    // Java program to demonstrate that we can sort // array elements in a single line import java.util.Arrays;  public class Main {     public static void main(String[] args)     {         int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};          // To sort a specific range of array in          // ascending order.         Arrays.sort(ar, 0, 4);         System.out.println("Sorted array in range" +                 " of 0-4 =>/n" + Arrays.toString(ar));          // To sort the complete array in ascending order.         Arrays.sort(ar);         System.out.println("Completely sorted order =>/n"                                    + Arrays.toString(ar));     } }

    Output:

    Sorted array in range of 0-4 => [1, 4, 6, 8, 3, 9, 7, 4, 2] Completely sorted order => [1, 2, 3, 4, 4, 6, 7, 8, 9]
  • 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. For this method to work properly, the array must first be sorted by the sort method.

    // Java program to demonstrate that we can do // binary search on array elements in a single line import java.util.Arrays;  public class Main {     public static void main(String[] args)     {         int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};                  // Sort the complete array in ascending order         // so that Binary Search can be applied         Arrays.sort(ar);          // To search for a particular value(for eg 9)         // use binarysearch method of arrays         int index = Arrays.binarySearch(ar,9);         System.out.println("Position of 9 in sorted"+                          " arrays is => /n" + index);      } }

    Output:

    Position of 9 in sorted arrays is =>  8
  • 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. The initial index of the range (from) must lie between zero and original.length, inclusive.

    // Java program to demonstrate that we can copy // an array or a subarray to a new array in single // line. import java.util.Arrays;  public class Main {     public static void main(String[] args)     {         int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};          // Copy the whole array         int[] copy = Arrays.copyOf(ar, ar.length);         System.out.println("Copied array => /n" +                             Arrays.toString(copy));          // Copy a specified range into a new array.         int[] rcopy = Arrays.copyOfRange(ar, 1, 5);         System.out.println("Copied subarray => /n" +                             Arrays.toString(rcopy));     } }

    Output:

    Copied array =>  [4, 6, 1, 8, 3, 9, 7, 4, 2] Copied subarray =>  [6, 1, 8, 3]
  • 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.

    // Java program to fill a subarray or complete // array with given value. import java.util.Arrays;  public class Main {     public static void main(String[] args)     {         int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};          // To fill a range with a particular value         Arrays.fill(ar, 0, 3, 0);         System.out.println("Array filled with 0 "+           "from 0 to 3 => /n" + Arrays.toString(ar));          // To fill complete array with a particular         // value         Arrays.fill(ar, 10);         System.out.println("Array completely filled"+                   " with 10=>/n"+Arrays.toString(ar));     } }

    Output:

    Array filled with 0 from 0 to 3 =>  [0, 0, 0, 8, 3, 9, 7, 4, 2] Array completely filled with 10=> [10, 10, 10, 10, 10, 10, 10, 10, 10]
  • public static List asList(T… a) It takes an array and creates a wrapper that implements List , which makes the original array available as a list. Nothing is copied and all, only a single wrapper object is created. Operations on the list wrapper are propagated to the original array. This means that if you shuffle the list wrapper, the original array is shuffled as well, if you overwrite an element, it gets overwritten in the original array, etc. Of course, some List operations aren’t allowed on the wrapper, like adding or removing elements from the list, you can only read or overwrite the elements. (Source Stackoverflow

    )

    // Java program to demonstrate asList() import java.util.Arrays; import java.util.List;  public class Main {     public static void main(String[] args)     {         Integer ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};          // Creates a wrapper list over ar[]         List<Integer> l1 = Arrays.asList(ar);          System.out.println(l1);     } }

    Output :

    [4, 6, 1, 8, 3, 9, 7, 4, 2]

  • This article is contributed by Rishabh Mahrsee . If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

    转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Array class in Java

    分享到:更多 ()

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址