gpt4 book ai didi

java - 如何使用可比较的属性来比较两个对象 - JAVA

转载 作者:行者123 更新时间:2023-12-01 10:44:46 24 4
gpt4 key购买 nike

我希望通过“int value”比较两个 Die 对象,并返回具有较高值的​​对象。我做错了什么......谢谢

public class Die implements DieIntf , Comparable {

private int value;

public Die(){}

class ComparatorId implements Comparator<Die> {

@Override
public int compare(Die t, Die t1) {
Integer d1 = t.getValue();
Integer d2 = t.getValue();
if(d1>d2) return 1;
else if(d1<d2) return -1;
else return 0;
}
}
}

最佳答案

Do not use Comparable/Comparator interface, until you have any requirement like sorting an object into ascending/descending order.

In your case, you want Bigger Object(based upon it's value) return while compare it.

所以做同样的事情

public class Die{

int value;


public Die compareMyDieObjce(Die d){

if(this.value > d.value){
return this;
}

return d;

}

@Override
public String toString() {
return " Object-Value : " + this.value;
}

public static void main(String[] args) {

Die d1 = new Die(); d1.value = 5;
Die d2 = new Die(); d2.value = 55;

System.out.println(d1.compareMyDieObjce(d2)); // Object-Value : 55

}

}

关于java - 如何使用可比较的属性来比较两个对象 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34253223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com