List<MyTest> myTestList =new ArrayList<>(); myTestList.add(new MyTest("1","2","3")); myTestList.add(new MyTest("2","3","1")); myTestList.add(new MyTest("3","2","1")); 使用java实现,求对象跟对象比同一个属性,最大值-0.5
时间: 2023-06-11 21:06:56 浏览: 75
ListTest.java
可以使用双重循环来比较每个对象之间的同一个属性的差值,计算最大值并减去0.5。代码如下:
```
double maxDiff = Double.MIN_VALUE;
for (int i = 0; i < myTestList.size() - 1; i++) {
MyTest obj1 = myTestList.get(i);
for (int j = i + 1; j < myTestList.size(); j++) {
MyTest obj2 = myTestList.get(j);
double diff = Math.abs(Double.parseDouble(obj1.getProperty()) - Double.parseDouble(obj2.getProperty()));
if (diff > maxDiff) {
maxDiff = diff;
}
}
}
maxDiff -= 0.5;
System.out.println("最大差值为:" + maxDiff);
```
其中,`MyTest`类是一个自定义的类,包含三个属性:`property1`、`property2`和`property3`。为了简化代码,这里只取了一个属性作为比较差值的依据。你需要将`getProperty()`方法替换成你要比较的属性的getter方法。
阅读全文