search

Home  >  Q&A  >  body text

java - Comparable[] 排序的问题

程序的结构大致如下

class   A {

sort(**Comparable[]  x**){
    //此处进行插入排序等
}

。。。main(String[] args)
{
    String[] arr={......}   //一个字符串数组
    A a=new A();
    a.sort(**arr**);
}
}

1.sort(...)方法需要的参数是一个Comparable数组,而arr是一个字符串数组,为什么可以直接传入arr那?
2.x[i]和a[i]表示同一个元素,为什么那?
3.这样写有什么好处那?

天蓬老师天蓬老师2778 days ago908

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 16:17:05

    String implements the Comparable interface, so every String object can be regarded as a Comparable object
    You can see the String source code

    public final class String implements java.io.Serializable, Comparable<String>, CharSequence 
     {
    public int compareTo(String anotherString) 
       {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;
    
        int k = 0;
        while (k < lim)
         {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) 
            {
                return c1 - c2;
            }
            k++;
         }
        return len1 - len2;
      }
    }
    

    This is to achieve polymorphism. For example, A extends B, then any object of subclass A can be regarded as an object of B;
    Similarly, A implements B, B is an interface, and any object of A can Can be regarded as an object of B.
    The advantage of writing this way is that many methods do not need to be overloaded. You don't need to write a sort method for every class, just write a sort method. Many other methods no longer require overloading.

    reply
    0
  • 迷茫

    迷茫2017-04-17 16:17:05

    1.String implements the Comparable interface, so it can be considered a Comparable type
    2 3 I don’t understand the question. . .

    reply
    0
  • Cancelreply