Why use arg type `class Object` instead of `Comparable[]`?

In the code below, I believe it would look more appropriate to make the method argument be of type Comparable[] instead of Object[].

The first reason it would be more appropriate is that one can be safe from runtime exceptions because every passed object has to implement interface Comparable. Second, every object in Java inherits from class Object so one can typecast any object as (Object) to use the methods of class Object.

package java.util; 
public class Arrays {
.........
public static void sort(Object[] a) {
        Object[] aux = (Object[])a.clone();
        mergeSort(aux, a, 0, a.length, 0);
    }
.........
}

Is there a reason why type Object[] is preferred over type Comparable[] as an argument type?

4

If you look at the mergeSort code you will see that it casts each member of array a to Comparable. If any object in the array is not a Comparable, a ClassCastException will be generated unless you have created a Comparator which knows how compare your objects and passed that to the sort method. Example of the two different techniques (comparable v comparator) here.

The Java developers decided that you should not be forced to add a Comparable interface to objects just because you want to store them in an array and may choose to sort them at some point. This gives you greater flexibility (and less cruft on your classes) at the minor risk of runtime failures rather than compile-time type checking. The flexibility is a win, in my opinion.

2

There is a problem caused by the way java arrays work, which is this: every array has its own type, which is not necessarily the same type as the objects contained in the array, and the type cannot be changed at runtime.

For example:

Object [] a= new Object[]{
   (Integer)5,
   (Integer)2
};

Arrays.sort ((Comparable [])a);

Would cause a class cast exception, despite the fact that all of the elements in a are comparable.

Now, you could argue that we shouldn’t create an Object array but rather a more specific type, but there’s another problem with that. Consider this code:

class GenericArrayExample<T extends Comparable>
{ 
    T[] a;

    GenericArrayExample(int size)
    {
        a = new T[size];
    }
    public void sort ()
    {
        Arrays.sort (a);
    }
 }

What’s the problem with this, you may ask: a is an array of Ts so should be comparable. There are two problems, however.

The first is that the constructor won’t compile, because in order to create the new array it needs to know the type of T at runtime, but Java can’t actually provide this information (google java generics erasure if you want to find out why). The usual solution is to use an array of objects instead. You could use Comparable [] instead, though, except:

Wouldn’t it be nice if we could use an instance of this class to store non-Comparable objects too? We’d have to avoid using the sort method, of course, and it should throw some kind of exception if we try to use it..

This can only be achieved, however, if a is an array of objects, which means Arrays.sort must accept object arrays.

Basically, Java types don’t always propagate nicely. If at any point, you cast to Object, you loose information about your types (this might not be always true in a block your compiler can analyze). And you can’t always avoid Object, due to generics.

Details

If we look at OpenJDK’s implementation, the comment says:

  1. Objects must implement Comparable
  2. Objects must be mutually comparable: you can’t compare String and Integer instances.

Both checks can be done at runtime (throwing exceptions if needed).
What you suggest enables to do the first check during compilation.

However, we must consider the method with respect to its usage, and unfortunately, you can’t always know the type of some objects.

I originally wrote an example with List<String> and toArray, which returns an Object[]. The conversion to Object[] does not allow calling sort and I saw no easy way to convert Object[] to String[]. Thanks to SJuan76’s comments, here is how to do it:

    String[] strings = names.toArray(new String[0]);

Then strings, thanks to array covariance, is suitable for comparison. However, this approach is not developper-friendly. Furthermore, it cannot be abstracted away by language constructs: generics use type erasing techniques that introduce Object instances.
By the way, let’s forget about generics for a moment: after all, early versions of Java, for which sort was implemented, did not provide generics.

As already said, the kind of code written above is certainly not convenient for use. But more importantly, even though it is checked at compile-time, I am pretty sure it is not optimized away: there is still an array copy operation at runtime: you don’t want to write an API which imposes this kind of cost to the user (also consider the performance of original virtual machines).

Then, it is better to simply accept more parameters and perform checks dynamically. Since anyway, point (2) above already requires runtime checks and possibly throws exceptions, we might as well accept Object[] and test types at runtime.

Now, you might think that the fact that some functions loose type informations like toArray (without argument) is itself unfortunate but this is more an issue of the language’s type system at this point.

7

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật