我在Java中使用了以下类,我希望将列表中的tocompare
个对象与之前的tocompare
对象进行比较,即将t2
与t1
进行比较。
我是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
}
答案 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());
}
}