`

关于Arrays.sort()方法用到的设计模式

阅读更多
    /**
     * Src is the source array that starts at index 0
     * Dest is the (possibly larger) array destination with a possible offset
     * low is the index in dest to start sorting
     * high is the end index in dest to end sorting
     * off is the offset to generate corresponding low, high in src
     */
    private static void mergeSort(Object[] src,
				  Object[] dest,
				  int low,
				  int high,
				  int off) {
	int length = high - low;

	// Insertion sort on smallest arrays
        if (length < INSERTIONSORT_THRESHOLD) {
            for (int i=low; i<high; i++)
                for (int j=i; j>low &&
			 ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
                    swap(dest, j, j-1);
            return;
        }

        // Recursively sort halves of dest into src
        int destLow  = low;
        int destHigh = high;
        low  += off;
        high += off;
        int mid = (low + high) >>> 1;
        mergeSort(dest, src, low, mid, -off);
        mergeSort(dest, src, mid, high, -off);

        // If list is already sorted, just copy from src to dest.  This is an
        // optimization that results in faster sorts for nearly ordered lists.
        if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
            System.arraycopy(src, low, dest, destLow, length);
            return;
        }

        // Merge sorted halves (now in src) into dest
        for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
            if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
                dest[i] = src[p++];
            else
                dest[i] = src[q++];
        }
    }

 

When we use the Arrays.sort(Object[] objects) static method to sort array of objects, we may find that it requires that the elements of the array implement the Comparable interface, as they need to be comparable to each other, it's the prerequisite. but how is it able to fulfil this? how does know whether the self-defined Object class has implemented the Comparable? we know actually it's the template pattern although it does extend something, but it's template, it implements something instread so that the algorithms defined in the sort method has been filled out or completed.

Yes, turn to the question about how does it know? after test, i get know that it solves this question by falling it into the Runtime Exception just like it displays that:

 

Exception in thread "main" java.lang.ClassCastException: MyString cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at Test.main(Test.java:14)

 

import java.util.Arrays;

public class Test {

	public static void main(String[] args) {
		MyString[] strings = {new MyString(2), new MyString(1)};
		Arrays.sort(strings);
		System.out.println(strings[0]);
	}

}

class MyString {
	int x;
	public MyString(int x) {
		this.x = x;
	}
}

 

the fact happens that sort is the helper method and mergeSort locates at the body of the sort method.

分享到:
评论

相关推荐

    JAVA竞赛编程题.pdf

    - 数组排序:`Arrays.sort()` 方法在这里用于对整数数组进行升序和降序排序。这是Java提供的一个便利的内置函数,可以对数组进行快速排序。 - 遍历数组:使用 `for` 循环遍历数组并打印元素,这展示了如何访问数组...

    有关学成成绩的java界面设计

    4. **排序算法**: 对成绩进行排序是常见的需求,可以使用Java内置的Arrays.sort()或Collections.sort()方法,或者自定义比较器实现。排序可以帮助用户更好地理解成绩分布,如按高分到低分排列。 5. **异常处理**: ...

    ACM中java的使用.pdf

    `Arrays.sort()`方法可用于对数组进行排序,而`Collections.sort()`用于列表。`BinarySearch`方法可以对已排序的数组或列表进行二分查找。 9. **算法实现**: Java可以方便地实现各种算法,如动态规划、贪心、...

    《剑指offer》Java版代码

    9. 设计模式:单例模式、工厂模式、装饰器模式等设计模式是面试中常见的问题,它们体现了良好的编程实践。 10. 接口与抽象类:接口定义了行为规范,抽象类则提供了部分实现,两者都是实现多态的方式。 在压缩包中...

    java进阶(文件读写、递归、数组排序、单体工厂模式)

    其中,`Arrays.sort()`方法是Java内置的通用排序函数,它可以对对象数组和基本类型数组进行排序。对于自定义类型的数组,需要实现`Comparable`接口或者提供`Comparator`来支持排序。 最后,我们来学习单体工厂模式...

    2021-2022计算机二级等级考试试题及答案No.12403.docx

    1. 数组排序:题目中的 `Arrays.sort(x)` 是Java中的数组排序方法,它会按照升序排列数组中的元素,因此选项A(2 7 8 12 35)是正确答案。 2. 字符串查找:`str.indexOf("大学","北京语言文化学院")` 在Java中表示...

    Java1.8.0_181 installation

    例如,`Arrays.sort(array, Integer::compareTo)`,这里就用到了方法引用来排序数组。 接口默认方法也是Java 8引入的新特性,它允许在接口中定义有实现的方法,而不必强制实现类去覆盖。这种设计模式使得在不破坏向...

    ASSIGNMENT

    你可以使用Java的`Arrays.sort()`方法,配合自定义的比较器(实现Comparable接口)来实现对象数组的排序。 4. **对象数组**:员工信息将被存储在一个对象数组中,每个对象代表一个员工,可以是`Employee`类的实例或...

    面试 java c c++ 数据结构 程序员

    面试中,面试官还可能考察你在实际项目中的应用,如内存管理(Java的垃圾回收与C/C++的手动内存管理)、并发编程(Java的synchronized关键字和线程池,C++的std::mutex和std::condition_variable)以及设计模式...

    JavaSe总结

    Java中可以使用`Arrays.sort()`方法对数组进行排序。 ```java int[] numbers = {5, 3, 1, 2, 4}; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers)); ``` ### ifconfig ifconfig 命令通常用于...

    CodeForces:CodeFroces 问题的解决方案

    2. **效率优化**:Java的性能优化是解决问题的关键,例如使用StringBuilder代替String进行字符串拼接,避免不必要的对象创建,使用Arrays.sort()而非Collections.sort()对原始类型数组排序等。 3. **递归与回溯**:...

    2021-2022计算机二级等级考试试题及答案No.13977.docx

    - **知识点**:`Arrays.sort()`方法用于对数组进行排序,默认采用升序排列。 - **应用场景**:在需要对数组中的数据进行排序处理时非常有用,可以快速实现数据排序。 ### 11. 二维数组定义 - **知识点**:在C语言...

    Java领域基础部分JavaSE笔记

    ##### 8.4 单例设计模式 - **定义**:确保一个类只有一个实例,并提供一个全局访问点。 - **实现**:饿汉式、懒汉式、双重检查锁定等。 ##### 8.5 final - **定义**:用于声明不可改变的变量、方法或类。 - **作用*...

    Competitive-coding:包含在不同编码平台上编写的代码

    3. **字符串处理**:Java中的String类提供了丰富的字符串操作方法,如模式匹配、子串查找、替换等,在处理文本和编码挑战时经常用到。 4. **递归与迭代**:递归和迭代是解决问题的两种基本思路,理解和掌握它们对于...

    _leetcode-python.pdf

    该标题表明此文件是一份关于LeetCode的Python解题集。LeetCode是一个面向程序员的在线编程题库,提供各种编程语言的算法和数据结构题目,用于帮助编程者提升技能,尤其是为了准备技术面试。Python是其中一种可用于...

Global site tag (gtag.js) - Google Analytics