Arrays

System.arraycopy---测试如下:

1 public class ArrayTest {
2         public static void main(String[] args) {
3             char[] src = {'a','b','c'};
4             char[] dest = new char[5];
5             System.arraycopy(src, 0, dest, 1, 2);
6             System.out.println(Arrays.toString(dest));
7         }
8     
9 }

输出结果:[ ,a,b, , ]

Arrays.copyOfRange--源码如下:

1   public static char[] copyOfRange(char[] original, int from, int to) {
2         int newLength = to - from;
3         if (newLength < 0)
4             throw new IllegalArgumentException(from + " > " + to);
5         char[] copy = new char[newLength];
6         System.arraycopy(original, from, copy, 0,
7                          Math.min(original.length - from, newLength));
8         return copy;
9     }
1  public static int[] copyOfRange(int[] original, int from, int to) {
2         int newLength = to - from;
3         if (newLength < 0)
4             throw new IllegalArgumentException(from + " > " + to);
5         int[] copy = new int[newLength];
6         System.arraycopy(original, from, copy, 0,
7                          Math.min(original.length - from, newLength));
8         return copy;
9     }

 Arrays.binarySearch

 1  public static int binarySearch(float[] a, int fromIndex, int toIndex,
 2                    float key) {
 3     rangeCheck(a.length, fromIndex, toIndex);
 4     return binarySearch0(a, fromIndex, toIndex, key);
 5     }
 6 
 7     // Like public version, but without range checks.
 8     private static int binarySearch0(float[] a, int fromIndex, int toIndex,
 9                      float key) {
10     int low = fromIndex;
11     int high = toIndex - 1;
12 
13     while (low <= high) {
14         int mid = (low + high) >>> 1;
15         float midVal = a[mid];
16 
17             int cmp;
18             if (midVal < key) {
19                 cmp = -1;   // Neither val is NaN, thisVal is smaller
20             } else if (midVal > key) {
21                 cmp = 1;    // Neither val is NaN, thisVal is larger
22             } else {
23                 int midBits = Float.floatToIntBits(midVal);
24                 int keyBits = Float.floatToIntBits(key);
25                 cmp = (midBits == keyBits ?  0 : // Values are equal
26                        (midBits < keyBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
27                         1));                     // (0.0, -0.0) or (NaN, !NaN)
28             }
29 
30         if (cmp < 0)
31         low = mid + 1;
32         else if (cmp > 0)
33         high = mid - 1;
34         else
35         return mid; // key found
36     }
37     return -(low + 1);  // key not found.
38     }

>>> 表示二进制右移(>>>1相当于/2)

计算机表示浮点数(float或者double类型)都有一个精度限制,对于超出了精度限制的浮点数,计算机会把他们超出精度之外的小数部分截掉,这样不想等的两个浮点数在计算机中用==进行比较的时候就有可能相等了。

因此,对于浮点数的比较可以直接使用>或者<,但是不能直接使用==。

对于float型的比较,先用Float.floatToIntBits转换成int类型的值,然后再用==操作符进行比较。

对于double型的比较,先用Double.doubleToLongBits转成long类型的值,然后再使用==操作符进行比较。

对于int的可以直接进行比较的,源码如下:

 1   private static int binarySearch0(byte[] a, int fromIndex, int toIndex,
 2                      byte key) {
 3     int low = fromIndex;
 4     int high = toIndex - 1;
 5 
 6     while (low <= high) {
 7         int mid = (low + high) >>> 1;
 8         byte midVal = a[mid];
 9 
10         if (midVal < key)
11         low = mid + 1;
12         else if (midVal > key)
13         high = mid - 1;
14         else
15         return mid; // key found
16     }
17     return -(low + 1);  // key not found.
18     }

 Arrays.equals 比较各种类型的数组对象是否相等(== 是比较地址空间,equals比较的是内容),此处只罗列值得关注的几个

 1   public static boolean equals(double[] a, double[] a2) {
 2         if (a==a2)
 3             return true;
 4         if (a==null || a2==null)
 5             return false;
 6 
 7         int length = a.length;
 8         if (a2.length != length)
 9             return false;
10 
11         for (int i=0; i<length; i++)
12         if (Double.doubleToLongBits(a[i])!=Double.doubleToLongBits(a2[i]))
13                 return false;
14 
15         return true;
16     }
 1  public static boolean equals(Object[] a, Object[] a2) {
 2         if (a==a2)
 3             return true;
 4         if (a==null || a2==null)
 5             return false;
 6 
 7         int length = a.length;
 8         if (a2.length != length)
 9             return false;
10 
11         for (int i=0; i<length; i++) {
12             Object o1 = a[i];
13             Object o2 = a2[i];
14             if (!(o1==null ? o2==null : o1.equals(o2)))
15                 return false;
16         }
17 
18         return true;
19     }

 Arrays.fill

 public static void fill(int[] a, int fromIndex, int toIndex, int val) {
        rangeCheck(a.length, fromIndex, toIndex);
        for (int i=fromIndex; i<toIndex; i++)
            a[i] = val;
    }

 Arrays.copyOf

1   public static char[] copyOf(char[] original, int newLength) {
2         char[] copy = new char[newLength];
3         System.arraycopy(original, 0, copy, 0,
4                          Math.min(original.length, newLength));
5         return copy;
6     }

 Arrays.copyOfRange

1  public static short[] copyOfRange(short[] original, int from, int to) {
2         int newLength = to - from;
3         if (newLength < 0)
4             throw new IllegalArgumentException(from + " > " + to);
5         short[] copy = new short[newLength];
6         System.arraycopy(original, from, copy, 0,
7                          Math.min(original.length - from, newLength));
8         return copy;
9     }

 

转载于:https://www.cnblogs.com/leehfly/p/4902675.html

<think>我们正在讨论Java中的Arrays.sort方法。根据用户提供的引用,我们可以总结出Arrays.sort的基本用法、示例以及一些高级用法(如自定义比较器)。用户需求:查找关于Arrays.sort的使用方法及示例。根据引用内容:1.Arrays.sort()可以对基本类型数组和对象数组进行排序,默认是升序排序。2.对于基本类型数组,使用示例见引用[1][4]。3.对于对象数组,可以使用自定义比较器(Comparator)来实现特定排序规则,如引用[5]所示。因此,回答应包含:1.基本类型数组排序示例。2.对象数组排序示例(自然排序和自定义比较器排序)。3.注意事项(如排序范围、稳定性等)。同时,根据系统指令,需要使用LaTeX格式表示数学表达式,但本题中数学表达式较少,主要关注代码示例和文字描述。最后,生成相关问题。回答结构:一、基本用法(基本类型数组)二、对象数组排序(自然排序和自定义排序)三、部分排序(指定范围)四、注意事项五、相关问题</think>### Java `Arrays.sort()` 方法详解与示例 `Arrays.sort()` 是 Java 中用于数组排序的核心方法,支持基本数据类型和对象数组的排序。以下是分类详解: --- #### **一、基本数据类型排序** 对整型、浮点型等基本类型数组进行**升序排序**(默认): ```java import java.util.Arrays; public class BasicSort { public static void main(String[] args) { int[] arr = {5, 2, 8, 1, 9, 3}; Arrays.sort(arr); // 原地修改原数组 System.out.println(Arrays.toString(arr)); // 输出: [1, 2, 3, 5, 8, 9] [^1][^4] } } ``` --- #### **二、对象数组排序** ##### 1. **自然顺序排序**(需实现 `Comparable` 接口) ```java String[] words = {"apple", "Banana", "cherry"}; Arrays.sort(words); // 按字典序排序(区分大小写) // 输出: ["Banana", "apple", "cherry"] ``` ##### 2. **自定义排序**(通过 `Comparator`) **示例 1:字符串长度排序** ```java Arrays.sort(words, (s1, s2) -> s1.length() - s2.length()); // 输出: ["apple", "Banana", "cherry"](按长度升序) ``` **示例 2:数字字符串拼接排序** ```java String[] numStrings = {"3", "30", "34", "9"}; Arrays.sort(numStrings, (s1, s2) -> Integer.parseInt(s2 + s1) - Integer.parseInt(s1 + s2) ); // 输出: ["9", "34", "3", "30"](形成最大数:934330)[^5] ``` --- #### **三、部分范围排序** 仅排序数组中指定范围的元素: ```java int[] arr = {7, 6, 1, 10, 23, 5}; Arrays.sort(arr, 1, 4); // 对索引[1,4)区间排序(即索引1到3) System.out.println(Arrays.toString(arr)); // 输出: [7, 1, 6, 10, 23, 5] [^4] ``` --- #### **四、多维数组排序** 按子数组首元素排序: ```java int[][] matrix = {{3, 5}, {1, 2}, {2, 4}}; Arrays.sort(matrix, (a, b) -> a[0] - b[0]); // 输出: [[1,2], [2,4], [3,5]] ``` --- #### **关键注意事项** 1. **原地修改**:直接修改原数组,不返回新数组[^1][^3] 2. **稳定性**:对象数组排序是稳定的(相等元素顺序不变) 3. **性能**: - 基本类型使用**双轴快速排序**($O(n \log n)$ 平均时间) - 对象类型使用**归并排序**(稳定且 $O(n \log n)$) 4. **自定义比较器**: - 返回负数:`a < b` - 返回 0:`a = b` - 返回正数:`a > b` > 通过合理选择自然排序或自定义 `Comparator`,可灵活处理各类排序需求[^2][^3]。 --- ### 相关问题 1. 如何实现 `Arrays.sort()` 的**降序排序**? 2. 对自定义对象数组排序时,`Comparable` 和 `Comparator` 接口如何选择? 3. `Arrays.sort()` 在多线程环境下是否安全? 4. 如何处理包含 `null` 值的对象数组排序?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值