Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the considerations for the use of Arrays.sort ()

Shulou Source: shulou.com Published: 2022-05-31 17:37:24 09月25日 Update

This article mainly explains "What are the precautions for the use of Arrays.sort()". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian slowly and deeply to study and learn "What are the precautions for the use of Arrays.sort()" together!

Arrays.sort() Notes

Data types in Java are divided into basic data types and reference data types

int: is the base data type, Integer is the reference data type

Ingeter: is the wrapper class of int, int initial value is 0, Ingeter initial value is null.

initialization

int num = 1;Integer num = new Integer(1);

With autoboxing and unboxing, you can also use: Integer num = 1;

Automatic boxing and unpacking

Autoboxing has been added since Java 5.0; automatic "unpacking" and "boxing" are "pre-processing" at compile time by JDK5 compilers.

Autoboxing: Encapsulate a primitive data type into an object type, and after becoming an object, you can call all the methods declared by the object.

Arrays.sort() is often used: there are two ways

The first is to reverse the array elements.

Arrays.sort(array,Collections.reverseOrder());

array must be a wrapper class object

The second type: array elements ascending or descending order

1. Rewrite Comparator default is ascending

List itemArrays.sort(y,new Comparator(){ @Override public int compare(Integer o1, Integer o2) { return o2-o1; //reverse is ascending }});

2. Code Simplification Using Lambada Expressions

Arrays.sort(array, (o1, o2) -> o2-o1);

In practice, we often use an array of primitive data types. At this time, if you use sort(), you need to convert the primitive data type to a reference data type, otherwise you will report an error.

sort() method source code:

public static void sort(T[] a, Comparator

Tags: Arrays types data items notes objects boxing elements ascending order packaging learning content initial values methods problems research compilation success one search code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology NVidia macOS Apple Huawei