Java Arrays class (three commonly used methods of Java arrays)


One, Arrays class introduction

  • This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows the array to be viewed as a list.
  • Unless otherwise noted, if the specified array reference is null, the methods in this class will throw a NullPointerException.

Second, the 静态methods in the Arrays class

Three methods are given for a detailed introduction, and the rest of the methods will be given below the main information of the API document

1.toString method

Method information: public static String toString(Array[] array)参数为数组
Output the array as a string in the default format

Code example

int[] arrInt = {
    
    55,44,33,22,11};
//使用toString方法遍历数组,省可以替代自己编写的for循环
String str = Arrays.toString(arrInt);
System.out.println(str);
//结果为:[55, 44, 33, 22, 11]

2.sort method

方法信息:public static String toString(Array[] array, int fromIndex, int toIndex)参数1数组,(Parameters 2, 3 can be absent) 参数2,3为数组索引位置,用来对指定范围的数据进行排序
Sort the array in ascending order

Code example

int[] arrInt = {
    
    55,44,33,22,11};
Arrays.sort(arrInt);
System.out.println(Arrays.toString(arrInt));
String[] arrStr1 = {
    
    "cc","bb","aa"};
Arrays.sort(arrStr1);
System.out.println(Arrays.toString(arrStr1));
//通过运算可知啊 = 21834,喔 = 21908,呃 = 21571
String[] arrStr2 = {
    
    "啊","喔","呃"};
Arrays.sort(arrStr2);
System.out.println(Arrays.toString(arrStr2));

【note】

If the parameter array
is sorted in numerical ascending order
by default , string (English) is sorted in ascending alphabetical order
, string (Chinese) is sorted in ascending order according to the encoding of the string.
If it is a custom type, then the custom class must have a comparable or Comparator interface support

3. Binary Search method

方法信息:public static int binarySearch(Array[] array, int fromIndex, int toIndex, data key)参数1数组(Parameters 2, 3 can be absent) 参数2,3为数组索引位置,用来对指定范围的数据进行排序参数4为要查找的值
Use 二分法查找the index position of the element in the array

Code example

int[] arrInt = {
    
    55,44,33,22,11};
//使用binarySearch方法前对数组进行排序
Arrays.sort(arrInt);
int  num = Arrays.binarySearch(arrInt, 44);
System.out.println("数字44在数组中的索引位置为:"+num);//结果为:数字44在数组中的索引位置为:3

【note】

Use binary search to search the specified array to obtain the specified value. This must be done 调用之前对数组进行排序(via the sort method). If the array is not sorted, the result is indeterminate. If the array 包含多个带有指定值的元素, then 无法保证找到的是哪一个.

4. Other methods

zheshiapiwendangdejietuzheshiapiwendangdejietuzheshiapiwendangdejietuzheshiapiwendangdejietuzheshiapiwendangdejietuzheshiapiwendangdejietuzheshiapiwendangdejietuzheshiapiwendangdejiejietuzheshiapihedanghetjiejietuzheshiapiwendanghedjiewenapiuzhewenapiuzhewenapiwendangapiwendangshiapiwendangdewenapiuzheapiwendangheapiwendanghet

Guess you like

Origin blog.csdn.net/weixin_44580492/article/details/106157685