Collections.sort(list)
和Collections.sort(list,null)
有什么区别我推测他们都按照自然顺序比较列表中的元素。Collections.sort没有编译时间错误
所以,我想这两个代码:
CODE 1:
List<Object> list=Arrays.asList("hello",123);
Collections.sort(list);
代码2:
List<Object> list=Arrays.asList("hello",123);
Collections.sort(list,null);
后者编译但前者没有给出预期编译器错误,类Object的实例不具有可比性。 为什么后者不给编译时间错误。
编辑:基于下面给出的评论。我明白为什么后者不给编译时间错误,但运行它会抛出ClassCastException : String cannot be converted into Integer
。它是如何推断,运行对象是字符串和整数的,因为我觉得
public static sort(List<Object> list) ---> Since list was of type object
{
// For instances of object in list call the compareTo method
}
}
'null'是一个有效的比较器。尝试运行它虽然... – Reimeus 2014-10-29 10:31:31
在运行它给出ClassCastException - java.lang.String不能转换为java.lang.Integer – user2653926 2014-10-29 10:32:27