我正在嘗試搜索數組列表以查找值(可能會重複出現)並刪除該值的所有實例。我也想從一個單獨的數組列表中刪除處於相同位置的值。 ArrayLists都是ArrayList<String>
。Java ArrayList搜索和刪除
比如我在ArrayList2尋找號碼5:
ArrayList 1 ArrayList2
cat 1
pig 2
dog 5
chicken 3
wolf 5
一旦我找到了5號,在這兩個位置,我想從ArrayList1去除狗與狼。我的代碼沒有錯誤,但它似乎並沒有真正刪除我所要求的。
//searching for
String s="5";
//for the size of the arraylist
for(int p=0; p<ArrayList2.size(); p++){
//if the arraylist has th value of s
if(ArrayList2.get(p).contains(s)){
//get the one to remove
String removethis=ArrayList2.get(p);
String removetoo=ArrayList1.get(p);
//remove them
ArrayList2.remove(removethis);
ArrayList1.remove(removetoo);
}
}
當我打印arrayLists時,它們看起來基本沒有改變。任何人看到我做錯了什麼?
你不想使用'Map'嗎?這將大大簡化這一過程。 –
Makoto
我不知道Map ...我會看到我能找到的東西。謝謝 –
Stephopolis
贊同@Makoto:爲什麼要維護兩個平行的列表?其他一些數據結構然後列表可能更合適 – bpgergo