简体   繁体   English

Collections.sort和Object []

[英]Collections.sort and Object[]

so just writing a Abstract classes and interfaces program. 因此只需编写一个Abstract类和接口程序。 my code so far: 到目前为止我的代码:

package lesson8;

import java.util.Collections;

public class ShapeTest {

 public static void main(String[] args) {
    Object[] shape = {new Square(4),
            new Rectangle(3, 2), 
            new RightTriangle(5,2), 
            new Square(2),
            new RightTriangle(2, 4),
            new Plus(3)};  
    Collections.sort(shape);
    }

}

my question is, why doesn't the Collection.sort() work with Object[]? 我的问题是,为什么Collection.sort()无法与Object []一起使用? how can i make it work? 我该如何运作? thanks! 谢谢!

You need to use Arrays.sort() to sort arrays (in place). 您需要使用Arrays.sort()对数组进行排序(就地)。 Moreover, there is no "natural" ordering for Object s, so you will have to pass a Comparator<Object> to the overloaded version of Arrays.sort() that takes a comparator, unless your Object s all implement Comparable and are all mutually comparable, as per this . 而且, Object没有“自然的”排序,因此您必须将Comparator<Object>传递给带有Comparator<Object>Arrays.sort()的重载版本,除非您的Object都实现Comparable并且相互之间都是可比, 据此

First of all, Collections.sort() expects a Collection as the argument, not an array. 首先, Collections.sort()Collection作为参数而不是数组。 For arrays you have Arrays.sort() . 对于数组,您可以使用Arrays.sort()

Second of all, in order for either Collection.sort() or Arrays.sort() to work for a Collection or array of Object s respectively, all these objects must be comparable to each other - they must implement the Comparable interface, and e1.compareTo(e2) must not throw a ClassCastException for each two elements of the Collection or array. 其次,为了使Collection.sort()Arrays.sort()分别适用于ObjectCollection或数组,所有这些对象必须彼此可比-它们必须实现Comparable接口,并且e1.compareTo(e2)不得为Collection或数组的每两个元素抛出ClassCastException

You could also use the BeanComparator from apache commons beanutils, like this: 你也可以使用BeanComparator从阿帕奇百科全书BeanUtils的,就像这样:

Collections.sort(personList, new BeanComparator("name"));

Example

Collections.sort work by calling the compareTo method on the objects in the array, in order to determine the natural ordering of the objects. Collections.sort通过在数组中的对象上调用compareTo方法来工作,以确定对象的自然顺序。 However, the class Object does not have a defined compareTo method, so the sort method has no way of knowing what the correct order is. 但是,类Object没有定义的compareTo方法,因此sort方法无法知道正确的顺序。 As such it cannot sort the list. 因此,它无法对列表进行排序。

If you want to sort the list using Collections.sort , then make sure all contained objects have a compareTo method defined. 如果要使用Collections.sort对列表进行排序,请确保所有包含的对象都定义了compareTo方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM