Arrays Common Methods of Manipulating Arrays in Java

The Arrays class contains various methods for manipulating [arrays] (such as sorting and searching). Also contains a static factory that allows converting an array to a List.

method describe
<T> List<T> asList(T… a) Returns a List constructed from the specified array
void sort(Object[] a) sort the array
void fill(Object[] a, Object val) assign the same value to all elements of an array
boolean equals(Object[] a, Object[] a2) Check if two arrays are equal
int binarySearch(Object[] a, Object key) Find Data Using Dichotomy on a Sorted Array

1. Arrays programming example

create a new one ArraysDemo.java

import java.util.Arrays;
import java.util.Random;

public  class  ArraysDemo {
     public  static  void  main ( String[] args ) {
         int [] arr = new  int [ 10 ];
         //Set the array elements to 9 
        Arrays.fill(arr, 9 );
        System.out.println("fill:" + Arrays.toString(arr));
        Random random = new Random();
         for ( int i = 0 ; i < arr.length; i++) {
             //Assign the array with random numbers within 100 
            arr[i] = random.nextInt( 101 );
        }
        //The reassigned array System.out 
        .println ( "Reassignment:" + Arrays.toString (arr));
         //Set the element with index 5 to 50 
        arr[ 5 ] = 50 ;
         //Sort
        Arrays.sort(arr);
        //sorted array System.out 
        .println ( "sorted: " + Arrays.toString (arr));
         //find the position of 50 int i = Arrays.binarySearch(arr, 50 );

        System.out .println ( "The index of the element whose value is 50: " +i);
         //Copy a new array int [] newArr = Arrays.copyOf(arr, arr.length);
         // Compare System.out 
        .println ( "equals:" +Arrays. equals (arr, newArr));

    }
}

Compile and run:

$  javac  ArraysDemo.java 
$  java  ArraysDemo 
fill: [9,  9 ,  9 ,  9 ,  9 ,  9 ,  9 ,  9 ,  9 ,  9 ] 
Reassign: [69,  83 ,  40 ,  58 ,  94 ,  42 ,  2 ,  53 ,  43 ,  83 ] 
sort after sorting: [2,  40 ,  43 ,  50 ,  53 ,  58 , 69 ,  83 ,  83 ,  94 ] 
Element index with value 50: 3 
equals: true

2. Practice questions

Create a new one  ArraysTest.java.

You need to complete the following requirements:

  • Sort the array [6, 17, 92, 32, 58, 22, 84, 66, 36, 33] using Arrays.
  • Find out where the sorted 33 is.
  • Test if you can find the value 33 without sorting?

import java.util.Arrays;

public class ArraysTest {
    public static void main(String[] args) {
        int[] arr = {6, 17, 92, 32, 58, 22, 84, 66, 36, 33};
        Arrays.sort(arr);
        System.out.println(Arrays.binarySearch(arr, 33));
    }
}

————————————————-the following No text ———————————————— ——

Leave a Comment

Your email address will not be published. Required fields are marked *