Java Comparator - 比较列表

时间:2018-02-15 15:54:49

标签: java comparator comparable

我在Java中使用了以下类,我希望将列表中的tocompare个对象与之前的tocompare对象进行比较,即将t2t1进行比较。

我是Java的新手,所以我对如何做到这一点并不了解。

public class ToCompare {
    private String property1;
    private String property2;

    public void getProperty1(){
        return property1;
    }
    public void setProperty1(String property1){
        this.property1 = property1;
    }

    public void getProperty2(){
        return property2;
    }
    public void setProperty1(String property2){
        this.property2 = property2;
    }
}

List<ToCompare> tocompare = new ArrayList();
ToCompare t1 = new ToCompare();
ToCompare t2 = new ToCompare();
ToCompare t3 = new ToCompare();
ToCompare t4 = new ToCompare();

tocompare.add(t1); //obj1
tocompare.add(t2); //obj2
tocompare.add(t3); //obj3
tocompare.add(t4); //obj4

for (String comp : tocompare) {
    // compare properties of 2nd ToCompare object with 1st ToCompare object
}

1 个答案:

答案 0 :(得分:0)

使用Comparable接口并实现定义比较策略的compareTo方法 - https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

例如,如果您想根据property1 -

进行比较
public class ToCompare implements Comparable<ToCompare> {
    private String property1;
    private String property2;

    public void getProperty1(){
        return property1;
    }

    public void setProperty1(String property1){
        this.property1 = property1;
    }

    public void getProperty2(){
        return property2;
    }

    public void setProperty1(String property2){
        this.property2 = property2;
    }

    @Override
    public int compareTo(ToCompare toCompare){  
        return this.getProperty1().compareTo(i.getProperty1()); 
   }  
}