java - Comparable[] 排序的问题
天蓬老师
天蓬老师 2017-04-17 16:15:05
0
2
903

程序的结构大致如下

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.这样写有什么好处那?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
Ty80

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.

迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template