简体   繁体   English

在Java中对ArrayList进行排序

[英]Collections.Sort an ArrayList in java

I use this function in java: 我在Java中使用此功能:

Collections.sort(an Arraylist, new CustomComparator);

The compare method in CustomComparator class will return an int. CustomComparator类中的compare方法将返回一个int。 What this means to the sort procedure? 这对排序程序意味着什么? what's the number of this value and how will affect the sorting procedure? 该值的数目是多少,将如何影响排序过程?

More specifically i want in compare method to compare two values. 更具体地说,我想在compare方法中比较两个值。 Here is my code: 这是我的代码:

    import java.util.Comparator;

    public abstract class CustomComparator implements Comparator<HLine> {
        @Override
        public int compare(HLine hl1, HLine hl2) {
            return hl1.y < hl2.y;
        }
    } 

and i call for sorting: 我呼吁排序:

    Collections.sort(hlines, new comparator());

hlines is an Arraylist of a object's with a Point and two doubles. hlines是具有Point和两个double的对象的Arraylist。 I want to compare the second double in two object's. 我想比较两个对象中的第二个double。

Basically, as stated in the Javadoc of Comparator.compare and Comparable.compareTo these methods return 基本上,如Comparator.compareComparable.compareTo的Javadoc中所述,这些方法将返回

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. 作为第一个参数小于,等于或大于第二个参数的负整数,零或正整数。

Meaning that if you call 意思是如果你打电话

new Integer(1).compareTo(0)

it will return a negative integer, which indicates, that 0 has to be ordered before 1. 它将返回一个负整数,表示必须在1之前对0进行排序。

new Integer(1).compareTo(1)

it will return 0, which indicates, that both values has to be ordered on the same level. 它将返回0,表示两个值必须在同一级别上排序。

new Integer(1).compareTo(2)

it will return a positive integer, which indicates, that 2 has to be ordered after 1. 它将返回一个正整数,表示2必须在1之后排序。

To fix your codesample, you need to rewrite compare() so it will return an Integer , as it is now it returns a boolean and will not compile. 要修复您的代码样本,您需要重写compare()以便它返回一个Integer ,因为现在它返回一个boolean并且不会编译。

Because you are trying to compare double s you can simply change to 因为您正在尝试比较double ,所以可以简单地更改为

    @Override
    public int compare(HLine hl1, HLine hl2) {
        return hl1.y - hl2.y;
    }

sort() method sort the elements but first they are compared.For the comparison purpose, sort() method can use compare() or compareTo() methods. sort()方法对元素进行排序,但首先将它们进行比较。出于比较的目的,sort()方法可以使用compare()或compareTo()方法。

Now, if you want to sort the elements on the basis of only one attribute the use compareTo() method of comparable interface. 现在,如果您只想基于一个属性对元素进行排序,请使用可比接口的compareTo()方法。

And if you want to sort the elements on the basis of more than one elements then use cmopare() method of comparator interface. 并且,如果要基于多个元素对元素进行排序,请使用比较器接口的cmopare()方法。

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

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