JavaRush /Java Blog /Random EN /Arrays class and its usage

Arrays class and its usage

Published in the Random EN group
Hello again! :) In the last lesson, we got acquainted with such a data structure as an array (Java array), learned how to create arrays, fill them with data, and also learned how they are stored in memory. Today we will look at some tasks and examples of working with arrays that you will often encounter in real work. For example, imagine this situation: we have an array of 10 numbers written in random order.
//array Java, example
int[] numbers = {167, -2, 16, 99, 26, 92, 43, -234, 35, 80};
Our task is to sort this array in ascending order: from smallest to largest numbers. In the end it should look like this:
[-234, -2, 16, 26, 35, 43, 80, 92, 99, 167]
How do we do this? The task is non-trivial, we have never done this before :/ Any ideas? Try to guess. Here's what we can do, for example:
  • Iterate through all elements of the array. Compare each element with the next ( [0]with [1], [1]with [2], [2]with , [3]etc.). If the current array element is larger than the next one, we swap them and move on to the next element. If not, leave it as is and move on.

  • Thus, after the first pass through the elements of the array, the largest value (167) is guaranteed to be in the last cell.

  • Now let's go through all the elements of the array again, starting with the element with index [0], but up to the penultimate element (the largest number is already in its place) and make the same comparisons and swaps. 
    At the end, in the penultimate cell we will have the second highest value (99).

  • Let's repeat this work as many times as we have minus one elements in the array.
Arrays class and its usage - 2We came up with the idea, all that remains is to write the code. It will look like this:
public class Main {

   public static void main(String[] args) {

       int[] numbers = {167, -2, 16, 99, 26, 92, 43, -234, 35, 80};

       for (int i = numbers.length - 1; i > 0; i--) {
           for (int j = 0; j < i; j++) {
           /* Compare the elements in pairs,
             if they are in the wrong order,
             then swap them */
               if (numbers[j] > numbers[j + 1]) {
                   int tmp = numbers[j];
                   numbers[j] = numbers[j + 1];
                   numbers[j + 1] = tmp;
               }
           }
       }

   }
}
Uh... Looks a little complicated -_- Even if the general principle of operation is clear, you have to write quite a lot of code to solve such a seemingly simple task. Okay, maybe we just overestimated ourselves? Probably, the task we have taken on is too difficult for us so far. Let's try to do something simpler. For example, let's take the same array of numbers.
int[] numbers = {167, -2, 16, 99, 26, 92, 43, -234, 35, 80};
Our task is to copy its contents to another array.
int [] numbersCopy = new int[10];
Think about how you would do this using the knowledge about arrays that you already have? You can, for example, loop through an array numbersand write its elements one by one into numbersCopy:
public class Main {

   public static void main(String[] args) {

       int[] numbers = {167, -2, 16, 99, 26, 92, 43, -234, 35, 80};

       int [] numbersCopy = new int[10];

       for (int i = 0; i < numbers.length; i++) {

           numbersCopy[i] = numbers[i];
       }

   }
}
Well, we've more or less done it! The problem seems to have been solved, but again: if it needs to be executed often, the code will have a bunch of identical loops. In fact, these and other problems have long been solved by the creators of Java, and we do not need to “reinvent the wheel” and write some code for our own solution.

Java Arrays class

A special Java class will help you solve typical problems when working with arrays - Arrays. Methods have been added to this class to solve the most common problems that Java programmers encounter in their work. For example, the task of sorting an array, for which we ourselves tried to come up with solutions, can be solved in one line:
public class Main {

   public static void main(String[] args) {

       int[] numbers = {167, -2, 16, 99, 26, 92, 43, -234, 35, 80};

       Arrays.sort(numbers);

       System.out.println(Arrays.toString(numbers));

   }
}
The method Arrays.sort()sorts the array. Moreover, the algorithm embedded in it makes this much more efficient than the code that we wrote. Console output:

[-234, -2, 16, 26, 35, 43, 80, 92, 99, 167]
Please note: to convert the array to a string, we used another class method Arrays- Arrays.toString(). Java arrays themselves do not override the toString(). So if you just write
System.out.println(numbers.toString());
toString()the class method will be called Object. In the case of arrays, the output will be something like this:

[I@4554617c
Now we won’t go into detail about why the conclusion is this way; the main thing is that this is clearly not what we need. But Arrays.toString() did what we wanted. By the way, our problem with copying is also easily solved in the class Arrays:
public class Main {

   public static void main(String[] args) {

       int[] numbers = {167, -2, 16, 99, 26, 92, 43, -234, 35, 80};

       int [] numbersCopy = Arrays.copyOf(numbers, numbers.length);
       System.out.println(Arrays.toString(numbersCopy));

   }
}
To the method Arrays.copyOf()we pass our original array (from which we need to copy the values) and the length of the new array into which we copy the data. In this case, we indicated as the length numbers.length, because we want to copy the entire array. If we want to copy only the first few elements, we can specify a smaller length for the new array:
public class Main {

   public static void main(String[] args) {

       int[] numbers = {167, -2, 16, 99, 26, 92, 43, -234, 35, 80};

       int [] numbersCopy = Arrays.copyOf(numbers, 4);
       System.out.println(Arrays.toString(numbersCopy));

   }
}
Here we have specified the length of the new array to be 4. Accordingly, only the first 4 elements numberswill be copied to the new array. Console output:

[167, -2, 16, 99]
By the way, if you need to copy part of an array, but not from the beginning, but “from the middle,” Arraysyou can do this too:
public class Main {

   public static void main(String[] args) {

       int[] numbers = {167, -2, 16, 99, 26, 92, 43, -234, 35, 80};

       int [] numbersCopy = Arrays.copyOfRange(numbers, 2,6);
       System.out.println(Arrays.toString(numbersCopy));

   }
}
Conclusion:

[16, 99, 26, 92]
The numbers from cells two ( inclusive ) to six ( not inclusive ) were copied into the new array. In addition, we may need to compare two arrays with each other. Just as with the method toString(), arrays themselves do not override the method equals(). So if we try to compare them like this:
public class Main {

   public static void main(String[] args) {

       int[] numbers = {1, 2, 3};
       int[] numbers2 = {1, 2, 3};

       System.out.println(numbers.equals(numbers2));
   }
}
we get the result false. Object.equals()After all, the method that compares links will be called . And of course they are different! But we need to compare the contents of the arrays, not the links. The class Arrayscontains an overridden method equals()that does exactly what we need:
public class Main {

   public static void main(String[] args) {

       int[] numbers = {1, 2, 3};
       int[] numbers2 = {1, 2, 3};

       System.out.println(Arrays.equals(numbers, numbers2));
   }
}
Conclusion:

true
By the way, the class Arraysworks successfully not only with ordinary arrays, but also with two-dimensional ones:
public class Main {

   public static void main(String[] args) {

       int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

       int[][] numbersCopy = Arrays.copyOf(numbers, numbers.length);

       System.out.println("Are these two-dimensional arrays equal to each other?");
       System.out.println(Arrays.deepEquals(numbers, numbersCopy));

       System.out.println(Arrays.deepToString(numbersCopy));
   }
}
Conclusion:

Равны ли эти двумерные массивы между собой?
true
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
As you can see, the method Arrays.copyOf()coped with copying a two-dimensional array. Please note that in this case, when copying a two-dimensional array, a so-called “shallow copy” occurs. And for comparing two-dimensional arrays and outputting them to the console, special methods are provided - deepEqualsand deepToString(); In the future, you will see more than once (and be happy about it) that the creators of Java foresaw a lot of typical situations that programmers encounter when working, and implemented ready-made solutions for them in the language. Using these solutions is much easier and more convenient than reinventing wheels, right? :) Be sure to read the class documentation Arrayson the Oracle website . Good luck with your studies!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION