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

The 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. In the end, it should look like this:
[-234, -2, 16, 26, 35, 43, 80, 92, 99, 167]
How can we do it? The task is not trivial, we have not done this before :/ Any ideas? Try to guess. For example, here is what we can do:
  • Loop through all the elements of the array. Compare each element with the next ( [0]s [1], [1]s [2], [2]s , [3]etc.). If the current array element is greater than the next, 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 do the same comparisons and swaps. 
    At the end, in the penultimate cell, we will have the second largest value (99).

  • Let's repeat this work as many times as we have in the array of elements minus one.
Arrays class and its use - 2We came up with the idea, it remains only 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;
               }
           }
       }

   }
}
Eh… Looks a bit 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 that we have taken is too difficult for us so far. Let's try to do something faster. 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 it, using the knowledge about arrays that you already have? You can, for example, loop through an array numbersand write its elements in turn to 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, here we are more or less done! The task seems to have been solved, at least again: if it needs to be performed often, there will be a bunch of identical cycles in the code. In fact, these and other tasks have long been solved by the creators of Java, and we do not need to “reinvent the wheel” and write some code of our own solution. Arrays class and its use - 3

Java Array class

A special Java class, Arrays. Methods have been added to this class to solve the most common tasks that Java programmers face at work. For example, the problem of sorting an array, for which we ourselves tried to come up with solutions, is 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 it much more efficient than the code that we wrote. Console output:

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

[I@4554617c
We will not now go into detail why the conclusion is exactly this, the main thing is that this is clearly not what we need. But Arrays.toString() did what we wanted. By the way, our copying task 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));

   }
}
In 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 specified 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 length for the new array less than:
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 as 4. Accordingly, only the first 4 elements numberswill be copied into the new array. Console output:

[167, -2, 16, 99]
By the way, if you need to copy part of the 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 the cells from the second ( inclusive ) to the sixth ( not inclusive ) were copied into the new array. In addition, we may need to compare two arrays with each other. Just like with a method toString(), arrays by themselves do not override a 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 references will be called . And of course they are different! But we need to compare the contents of arrays, not 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 Arrayssuccessfully works 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 as well. 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 their output to the console, special methods are provided - deepEqualsand deepToString(); In the future, you will see more than once (and rejoice at this) that the creators of Java have provided for a lot of typical situations that programmers face when working, and have implemented ready-made solutions for them in the language. Using these solutions is much easier and more convenient than reinventing the wheel, right? :) Be sure to read the class documentation Arrayson the Oracle website . Good luck with your learning!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION