我有一个问题,我知道如何对整数数组进行排序并找到最大值,但是当我有对象(矩形)的数组列表时我不知道该怎么做,请有人帮助解决这个算法。
这是我所做的:
public static Rectangle largest(ArrayList < Rectangle > rectangles) {
Rectangle max = rectangles.get(0);
for (Rectangle temp: rectangles) {
if (temp.getArea() > max.getArea())
max = temp;
}
return max;
}
最佳答案
如果您是该程序的设计者,您可以制作 Rectangle
实现Comparable<Rectangle>
public class Rectangle implements Comparable<Rectangle> {
// existing code
public int compareTo (Rectangle r) {
return Integer.compare(this.area, r.getArea());
}
}
然后只需使用 Collections#sort
Collections.sort(rectangles);
<小时/>
如果您使用此版本的 java,您可能需要定义 Comparator
sort
内使用 lambda
的方法表达。
Collections.sort(rectangles, (rectangleOne, rectangleTwo) -> Integer.compare(rectangleOne, rectangleTwo));
关于java - 带有对象的ArrayList,排序并找到最大的对象(按面积排列的矩形),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371621/