array doesn't automatically sort comparable objects

时间:2019-03-06 11:35:40

标签: java

I have a class box with 3 double values. The task is to sort one of the values and print the results. Below there is a code

 public class Box implements Comparable<Box> {

        private double x;
        private double y;
        private double z;
        private double volume;

@Override
    public int compareTo(Box o) {
        return this.x > o.x ? 1 : this.x < o.x ? -1 : 0;
    }

    public static void  sorting (Box[] o)
    {
        System.out.println();
        for (int i = 0; i<o.length; i++)
        {
            System.out.println(o[i].x);
        }
    }

There is no errors in this code, but it is not sorting x parameter too.

3 个答案:

答案 0 :(得分:1)

Java中的数组不会自动排序(通常也不是集合)。对于数组,您需要调用

Arrays.sort(boxes);

如果使用集合,则可以使用以下方式对现有列表进行排序

Collections.sort(boxList);

或改为使用SortedSet / Map(例如TreeSet)。这些类型的集合会在插入时自动对其元素进行排序,并保持自然顺序。

正如@AndyTurner所指出的那样,Sets and Maps当然会丢弃重复的内容(取决于您对hashCodeequals的实现)。

This question,而且很好的答案也与之相关,并且总体上很好地概述了Java中的集合排序。

答案 1 :(得分:1)

实施Comparable仅表示该类为其实例提供某些默认顺序。 这不是不是,这意味着每个数组或集合都必须自动应用该顺序

例如,String类还实现了Comparable,它提供了 lexicographical 顺序,但是您仍然可以决定将字符串放置在数组中的位置。可能是因为您这样做

array[index] = element;

element放置位置的决定仅{strong>取决于index,而不取决于element的任何特征。

要使用元素的 default 顺序对数组进行排序,可以使用Arrays.sort(o);,否则数组o将元素保留在索引指定的位置。

答案 2 :(得分:-1)

您实际上有几种选择。他们中的一些人正在创建您自己的排序功能,或者使用具有适当比较器的Collection排序。您可能需要检查this SO topic以获得该主题的更多详细信息。另外,请记住在发布之前使用搜索,这是键入“ java sort by object field”之类的东西后弹出的第一件事。

相关问题