我正面臨着一個奇怪的問題。在下面的代碼片段中,當我調用userRoles.removeRole(strRole)時,第二個for循環在一次迭代後破壞。列表中有2個元素。第一個for循環執行兩次。但是第二個只執行一次。該方法調用返回布爾值。任何人都可以請幫我在我的代碼中有什麼問題?Java:由於方法調用,for循環在所有迭代之前打破了
if(userRoles != null)
{
List<String> roles = userRoles.getRoles();
String strUserName = userRoles.getUserName();
for(String strRole: roles)
{
System.out.println("role : " + strRole);
}
//for(String strRole: roles)
for(int count = 0; count < roles.size() ; count++)
{
String strRole = roles.get(count);
System.out.println("role before check: " + strRole);
if(ur.hasRoleForUser(strRole, strUserName))
{
System.out.println("role after check: " + strRole);
userRoles.removeRole(strRole);
}
}
System.out.println("role length: " + userRoles.getRoles().size());
if(userRoles.getRoles().size() > 0)
{
ur.addUserRoles(userRoles);
}
blnSuccess = true;
}
請顯示removeRole(str)方法在做什麼。 – Abdulgood89
爲什麼它會很奇怪?您正在從您列舉的列表中刪除一個項目。 2 - 1 = 1。'getRoles'顯然返回對同一個列表'removeRole'的引用縮短。 –
@MargaretBloom是的,你是對的...我沒有注意到它...我認爲它作爲新的對象,這並沒有指對象的列表,從中刪除項目。謝謝您的回覆。 – NPException