java Arrays method

java Arrays method

The Arrays class in Java is a utility class that provides several static methods for working with arrays. It is part of the java.util package and can be used to perform a variety of tasks on arrays, such as sorting, searching, filling, and comparing.

Here are some common methods of the Arrays class:

  • sort(): Sorts the elements of an array in ascending order.
  • binarySearch(): Searches for a specified element in a sorted array using the binary search algorithm.
  • fill(): Fills an array with a specified value.
  • equals(): Compares two arrays for equality.
  • copyOf(): Copies an array to a new array with a specified length.
  • copyOfRange(): Copies a range of elements from an array to a new array.
  • asList(): Returns a fixed-size list backed by the specified array.

Here is an example of how to use the sort() and binarySearch() methods of the Arrays class:

import java.util.Arrays;

public class ArraysExample {

    public static void main(String[] args) {
        int[] numbers = { 3, 7, 1, 4, 9, 2, 5, 8, 6 };

        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));  // [1, 2, 3, 4, 5, 6, 7, 8, 9]

        int index = Arrays.binarySearch(numbers, 5);
        System.out.println(index);  // 4
    }
}
Source:‮ual.www‬tturi.com

This code creates an array of integers called numbers and initializes it with some values. It then calls the sort() method of the Arrays class to sort the elements of the numbers array in ascending order. The sort() method uses the quick sort algorithm to sort the array.

The code then calls the binarySearch() method of the Arrays class to search for the element 5 in the numbers array. The binarySearch() method returns the index of the element if it is found in the array, or a negative number if it is not found. In this case, the element 5 is found at index 4, so the binarySearch() method returns 4.

You can also use the toString() method of the Arrays class to convert an array to a string. The toString() method returns a string representation of the array, containing the elements of the array separated by commas and enclosed in square brackets.

For example:

System.out.println(Arrays.toString(numbers));  // [1, 2, 3, 4,
Created Time:2017-11-03 00:14:42  Author:lautturi