2014-11-08 23 views
-4
public void addSampleData(){ 
    userList.add(new User("n45","sfdsf","sfgfsg")); 

我想通過數組進行迭代,並能夠識別並刪除基於其字符串值即「sfdsf」,而不是它的ArrayList中位置的對象。迭代數組中查找的字符串值

+0

你是怎麼定義用戶類的? – SMA 2014-11-08 15:01:42

+0

ArrayList userList; – 2014-11-08 15:07:34

+0

我需要用戶類的定義。我可以弄清楚用戶列表是什麼。 – SMA 2014-11-08 15:09:24

回答

0

你可以簡單地使用for循環陣列上迭代(或者一個基本的或增強的環):

for (User user : userList) { 
    // Do whatever you want on the item in the current iterator position 
} 

如果你想物色對象,並可能把它比作其他對象,你有以覆蓋equalshashCode方法。 (更好的上this link主題)

如果你只考慮你所提到的領域,sfdsf,是你User標識符,那麼你可以使用實例變量在您的比較;例如:

for (int i = 0; i < userList.size(); i++) { 
    if ("sfdsf".equals(user.getYourField())) { // Note that getYourField refers to your subject field accessor 
    userList.remove(i); // Remove the item if it matches the criteria 
    } 
}