I have following problem. I want to take a list with a method, find a value within that list and replace it with another.
void replaceAll( ArrayList arr, Integer toFind, Integer replacement) {
int indexOfArray = arr.indexOf(toFind);
if(arr.contains(toFind)) {
for(int x = 0; x < arr.size(); x++) {
if (arr.contains(toFind)) {
arr.remove(toFind);
arr.add(indexOfArray, replacement);
}
}
}
}
This is the solution I have worked out for myself and it most certainly works. However, I think it can be done more cleanly without the usage of a for loop. Could someone tell me how?
解决方案
There is a built in method to do exactly this operation:
Collections.replaceAll(list, foo, bar);