這是我的代碼,構建一個可能的城市之旅Locale l
(這不是最佳的,它只是讓我的AI搜索領先)。不確定ConcurrentModificationException的原因
我得到ConcurrentModificationException
,據我所知,當多個代碼片段訪問變量/集合並嘗試修改它時。造成這一代碼來獲得不高興:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
我修改爲我添加的元素,但隨着迭代器不具有添加一個方法(只刪除),我使用的是集合的方法。
所以,我的問題是:
- 是我加入什麼導致問題的因素?
- 如果是這樣,我如何正確添加它,以便
modCount
正確,我沒有得到ConcurrentModificationException
?
全部下面的方法,就行了,其中ConcurrentModificationException
發生註釋:
public void construct() {
tour = new ArrayList();
ArrayList<City> lcl = new ArrayList(l.getCitys());
tour.add(lcl.remove(0));
tour.add(lcl.remove(1));
while (!this.tourComplete()) {
System.out.println(tour.size());
Iterator tourit = tour.iterator();
City g1 = (City) tourit.next();
City g2 = (City) tour.get(lcl.indexOf(g1)+1);
int gapDist = l.distanceBetweenCitys(g1, g2);
while (tourit.hasNext()) {
City C = null;
int best = Integer.MAX_VALUE;
for (Iterator lclit = lcl.iterator(); lclit.hasNext();) {
City c = (City) lclit.next();
int avg = (l.distanceBetweenCitys(g1,c) +
l.distanceBetweenCitys(g2, c))/2 ;
if ((avg<gapDist) && (avg<best)) {
C = c;
best = avg;
}
}
if (C != null) {
assert(best == Integer.MAX_VALUE);
City A = tour.get(0);
City Z = tour.get(tour.size()-1);
boolean begin = true;
for (Iterator lclit = lcl.iterator(); lclit.hasNext();) {
City c = (City) lclit.next();
int dist = l.distanceBetweenCitys(A,c);
if (dist<best) {
begin = true;
C = c;
best = dist;
}
}
for (Iterator lclit = lcl.iterator(); lclit.hasNext();) {
City c = (City) lclit.next();
int dist = l.distanceBetweenCitys(Z,c);
if (dist<best) {
begin = false;
C = c;
best = dist;
}
}
if (begin) {
// one of these is causing the problem
tour.add(0,C);
}
else {
// one of these is causing the problem
tour.add(C);
}
}
else {
// one of these is causing the problem
tour.add(tour.indexOf(g2),C);
}
g1 = (City) tourit.next(); // this is where it all goes wrong
g2 = (City) tour.get(lcl.indexOf(g1)+1);
gapDist = l.distanceBetweenCitys(g1, g2);
}
}
}
我一看到異常就想到了1&2 我的代碼大致是在每對城市之間插入最好的城市,直到所有的城市都在參觀,因此每個城市都需要在自己身後才能完成隨着新配對的形成而增加 看起來,3我是我的最佳選擇,我現在就開始修復。 雖然SO回到我身邊,但我想到了一個可能的數字5,它將採用main while循環的內容並將其變爲方法,並遞歸解決此問題,從而不使用迭代器,並希望避免異常 感謝所有幫助^ _^ – Gwilym 2009-12-22 13:25:08
+1。第一句話是重要的一句話...... – Jared 2009-12-22 15:23:09