-4

Here ArrayList & its parent class & interface never implemented Comparable, Still the Collections.sort(al) compiled without an error ?

public class Collections_Demo {

    public static void main(String[] args) {

        ArrayList al= new ArrayList();
        al.add("ram");
        al.add("shaym");

        Collections.sort(al);
    }
}
Draken
  • 3,134
  • 13
  • 34
  • 54
Amartya
  • 29
  • 3
  • 6
    It's not `ArrayList` that needs to be `Comparable`, it's `String` - and it is. – daniu Sep 03 '18 at 07:21
  • 1
    This code would be compiled with a raw types warning. Use `ArrayList al= new ArrayList<>();` – Andy Turner Sep 03 '18 at 07:23
  • `public static > void sort(List list)` so `T` needs to extend `Comparable`, in your case `T` is `String` – Shloim Sep 03 '18 at 07:24
  • Also: dont use raw types: https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – GhostCat Sep 03 '18 at 07:26

2 Answers2

1

Look at signature of sort#method

public static <T extends Comparable<? super T>> void sort(List<T> list) {
    list.sort(null);
}

This means that not list should implement Comparable to be able to sorted, but type of list elements.

In your case String implements Comparable, so code compile and run without exeptions

Oleg Zinoviev
  • 549
  • 3
  • 14
  • OP's is able to compile not because `String` implements `Comparable`, but because OP is using raw types. – Sweeper Sep 03 '18 at 07:30
  • Sure. Exception will be thrown only when sort will be invoked and under the hood elements will be cast to Comparable – Oleg Zinoviev Sep 03 '18 at 07:35
0

First, ArrayList needs not be Comparable. The things inside the array list need to be Comparable. This is the signature of sort:

public static <T extends Comparable<? super T>> void sort(List<T> list) {

T is constrained, not the List.

However, using raw types changes everything.

Because you wrote ArrayList instead of ArrayList<String>, you are using the raw type of ArrayList. This basically erases all generic type parameters and makes sort not check for any constraints. It is as if the signature became:

public static void sort(List list) {

That's why you were able to call it. Had you put non-Comparable things into the array list, it would have crashed at runtime:

ArrayList al= new ArrayList();
al.add(new Object());
al.add(new Object());

Collections.sort(al); // ClassCastException
Sweeper
  • 213,210
  • 22
  • 193
  • 313