android细节之java.util.ConcurrentModificationException异常

今天在做android项目的时候,遇到了这个异常,好吧,其实平常遇到最多的异常是IllegalstateException,都是跟我们硬件相连的SDK抛出来的,把我折磨的欲生欲死啊。扯远了。说回到今天的这个异常,java.util.ConcurrentModificationException异常,一开始我愣了一下,貌似从来没遇到过这个,然后果断百度大神,这才发现:

原因是你遍历该集合时,对该集合进行了删除元素的操作导致的,如果你有删除元素的必要,建议赋值到另一个集合,然后对他进行删除操作.

偶出现错误的地方:

if (serverCards != null) {
			for (PaymentCard serverCard : serverCards) {
				MstCard matchingMstCard = findMatchingMstCard(serverCard,
						mstCards);
				ChargecaseCard matchingChargecaseCard = findMatchingChargecaseCard(
						serverCard, chargecaseCards);
				if (matchingMstCard != null && matchingChargecaseCard != null) {
					matchingMstCard.setDominantColor(serverCard
							.getDominantColor());
					matchingChargecaseCard.setDominantColor(serverCard
							.getDominantColor());
					unifiedCards.add(new UnifiedCard(matchingMstCard,
							serverCard, matchingChargecaseCard));
					mstOnlyCards.remove(matchingMstCard);
					chargecaseOnlyCards.remove(matchingChargecaseCard);
				} else if (matchingMstCard != null
						&& matchingChargecaseCard == null) {
					matchingMstCard.setDominantColor(serverCard
							.getDominantColor());
					unifiedCards.add(new UnifiedCard(matchingMstCard,
							serverCard));
					mstOnlyCards.remove(matchingMstCard);
				} else if (matchingMstCard == null
						&& matchingChargecaseCard != null) {
					matchingChargecaseCard.setDominantColor(serverCard
							.getDominantColor());
					unifiedCards.add(new UnifiedCard(serverCard,
							matchingChargecaseCard));
					chargecaseOnlyCards.remove(matchingChargecaseCard);
				} else {
					serverOnlyCards.add(serverCard);
				}
			}
		}

		for (MstCard card : mstOnlyCards) {
			ChargecaseCard matchingChargecaseCard = findMatchingChargecaseCard(
					card, chargecaseCards);
			if (matchingChargecaseCard != null) {
				matchingChargecaseCard
						.setDominantColor(card.getDominantColor());
				unifiedCards.add(new UnifiedCard(card, null,
						matchingChargecaseCard));
				chargecaseOnlyCards.remove(matchingChargecaseCard);
			} else {
				unifiedCards.add(new UnifiedCard(card));
			}
		}

		for (ChargecaseCard card : chargecaseOnlyCards) {
			unifiedCards.add(new UnifiedCard(card));
		}

		for (PaymentCard card : serverOnlyCards) {
			unifiedCards.add(new UnifiedCard(card));
		}

		return unifiedCards;
在一个for循环中mstOnlyCards调用了,mstOnlyCards.remove()方法。


特记录之,引以为戒。


 

android细节之java.util.ConcurrentModificationException异常,布布扣,bubuko.com

android细节之java.util.ConcurrentModificationException异常

上一篇:android设备不自带sqlite3问题(sqlite3 not found)


下一篇:Android中的使用