我將此遞歸BubbleSort算法添加到我在lwjgl上運行的遊戲中。我試圖用一個浮點數來排序「雲」對象的ArrayList,這是這個雲的速度。BubbleSort StackOverflowError
出於某種原因,有時我會在我調用本身的方法的行處得到一個「java.lang.StackOverflowError」。
下面的代碼:
public void sort() {
for (int i = 0; i < clouds.size() - 1; i++) {
Cloud cl1 = clouds.get(i);
Cloud cl2 = clouds.get(i + 1);
if (cl1.getSpeed() < cl2.getSpeed()) {
continue;
}
clouds.set(i, cl2);
clouds.set(i+1, cl1);
this.sort();
}
}
,這裏是我得到的錯誤:
Sat May 04 20:28:45 CEST 2013 ERROR:null
java.lang.StackOverflowError
at backgrounds.Clouds.sort(Clouds.java:224)
[...] // The line above is repeated for some hundred times.
我推薦在你的Cloud類中實現可比較的,你使用一個集合來保存它看起來像的雲(.size),所以Collections.sort()會爲你處理它。發明自己的方法雖然很有趣;) – arynaq 2013-05-04 18:55:20