简体   繁体   English

什么时候在 Java 中使用 Comparable[]?

[英]When to use Comparable[ ] in Java?

I was watching over a code which was using Comparable[] as an array that is exactly working as a collection framework list.As the task was done easily by using it without too many loops, is it a good practice to use it for other data types?我正在查看使用Comparable[]作为数组的代码,该数组完全用作集合框架列表。由于使用它可以轻松完成任务而没有太多循环,因此将它用于其他数据是否是一个好习惯类型?

public class MergeSortExample {

public Comparable[] mergeSort(Comparable[] inputList) {
    if(inputList.length <= 1) {
        return inputList;
    }
    Comparable[] list1 = new Comparable[inputList.length/2];
    Comparable[] list2 = new Comparable[inputList.length - list1.length];
    System.arraycopy(inputList, 0, list1, 0, list1.length);
    System.arraycopy(inputList, list1.length, list2, 0, list2.length);

    mergeSort(list1);
    mergeSort(list2);

    merge(list1, list2, inputList);
    return inputList;
}

public void merge(Comparable[] list1, Comparable[] list2, Comparable[] resultList) {
    int indexOfList1 = 0;
    int indexOfList2 = 0;
    int indexOfMergedList = 0;

    while(indexOfList1 < list1.length && indexOfList2 < list2.length) {
        if(list1[indexOfList1].compareTo(list2[indexOfList2]) < 0) {
            resultList[indexOfMergedList] = list1[indexOfList1];
            indexOfList1++;
        }else {
            resultList[indexOfMergedList] = list2[indexOfList2];
            indexOfList2++;
        }
        indexOfMergedList++;
    }
    System.arraycopy(list1, indexOfList1, resultList, indexOfMergedList, list1.length - indexOfList1);
    System.arraycopy(list2, indexOfList2, resultList, indexOfMergedList, list2.length - indexOfList2);
}

} }

In the old days before generics, collections could only use Object and were not type-safe.在泛型出现之前的过去,集合只能使用Object而不是类型安全的。 Arrays have always been type-safe.数组一直是类型安全的。 In those days it was common to use arrays for that reason.在那个时候,出于这个原因使用数组是很常见的。 In modern code I would normally prefer to use a list in general-purpose code, but there is nothing wrong with arrays.在现代代码中,我通常更喜欢在通用代码中使用列表,但数组没有任何问题。 The collections are implemented using arrays internally and sometimes an array is just what you want.集合是在内部使用数组实现的,有时数组正是您想要的。 Hard to give a better answer without seeing more of your code!很难在没有看到更多代码的情况下给出更好的答案!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM