简体   繁体   English

int []与可比[]在Java中,什么时候使用?

[英]int[] Vs comparable[] in java, when to use?

While I was implementing Merge Sort, I found this piece of code: 在实现“合并排序”时,我发现了这段代码:

    public static void merge(Comparable[] a, int lo, int mid, int hi)
    { // Merge a[lo..mid] with a[mid+1..hi].
        int i = lo, j = mid+1;
        for (int k = lo; k <= hi; k++) // Copy a[lo..hi] to aux[lo..hi].
            aux[k] = a[k];
        for (int k = lo; k <= hi; k++) // Merge back to a[lo..hi].
            if (i > mid) 
                a[k] = aux[j++];
            else if (j > hi )
                a[k] = aux[i++];
            else if (less(aux[j], aux[i]))
                a[k] = aux[j++];
            else 
                a[k] = aux[i++];
     }


This one merges the sub arrays one by one! 这一步将子数组一一合并! But what confuses me is the fact, in the parameter,why is Comparable[] a used when this can still be solved using int[] a . 但是令我感到困惑的是,在仍然可以使用int[] a来解决的情况下,为什么使用了Comparable[] a这个参数。 Does the usage of Comparable add any performance tweak in this case? 在这种情况下,使用Comparable是否会增加性能调整? From other answers I found, 从我发现的其他答案中,

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this. 如果要定义所讨论对象的默认(自然)排序行为,请使用Comparable,通常的做法是为此使用对象的技术或自然(数据库?)标识符。

Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour. 如果要定义外部可控制的订购行为,请使用Comparator,这可以覆盖默认的订购行为。

The question is : does the usage of Comparable[] improves the efficiency of this code in any bit? 问题是Comparable[]的使用是否在任何程度上提高了此代码的效率?

The usage of Comparable[] does not improve the efficiency of the code that you shown at all. 使用Comparable[]根本不会提高您显示的代码的效率。

The code that you shown works with any array of objects that are Comparable not only int s. 您显示的代码不仅可用于int ,而且可用于任何Comparable的对象数组。

All the difference could be noticed in the less method execution, which is not shown in your question but that I assume it is something like return a.compareTo(b) < 0; 所有的差异都可以在less方法执行中注意到,这在您的问题中没有显示,但我认为这类似于return a.compareTo(b) < 0; .

If any efficiency difference could be noticed, it would be due to the compareTo method implementation of your Comparable objects. 如果发现效率差异,则可能是由于Comparable对象的compareTo方法实现所致。

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

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