public class RectangleComparator implements Comparator<Rectangle2D> {
double x1;
double x2;
double y1;
double y2;
double w1;
double w2;
double h1;
double h2;
@Override
public int compare(Rectangle2D o1, Rectangle2D o2) {
x1 = o1.getX();
x2 = o2.getX();
y1 = o1.getY();
y2 = o2.getY();
w1 = o1.getWidth();
w2 = o2.getWidth();
h1 = o1.getHeight();
h2 = o2.getHeight();
int result = -1;
if (x1 == x2)
result = 0;
if (result == 0)
{
if (y1 == y2)
result = 0;
}
if (result == 0)
{
if (w1 == w2)
result = 0;
}
if (result == 0)
{
if (h1 == h2)
result = 0;
}
return result;
}
public class RectangleTester {
public static void main(String[] args)
{
ArrayList <Rectangle2D> rect = new ArrayList<Rectangle2D>();
rect.add(new Rectangle2D.Double(20,15,14, 10));
rect.add(new Rectangle2D.Double(20,16,11, 5));
rect.add(new Rectangle2D.Double(17,28,90, 100));
rect.add(new Rectangle2D.Double(15,9,60, 75));
rect.add(new Rectangle2D.Double(41,56,21, 19));
Collections.sort(rect, new RectangleComparator());
for (Rectangle2D temp : rect)
System.out.println(temp.toString());
}
}
}
嗨,我試圖通過編寫一個小程序來排序矩形列表學習比較。但是,當我運行這個輸出是原始列表的反向,而不是一個排序列表。我不太瞭解比較,如果你們能提供一些幫助,我會很感激,謝謝。collections.sort沒有排序arraylist
如何你認爲Rectangle2D是用於比較的嗎?你的比較器邏輯對我來說沒有意義.Pls也把Rectangle2D的源代碼也放在你的頭上。你需要先調整你的比較器邏輯,因爲我看到你用-1提供了默認值,這意味着它大部分會反轉除非您的比較器邏輯工作 –