I have the following code:
Widget[] widgetArray = widgetService.getAllWidgets();
List<Widget> widgets = Arrays.asList(widgetArray);
// Prune out any Widgets named "Melvin".
Iterator<Widget> iter = widgets.iterator();
while(iter.hasNext()) {
Widget w = iter.next();
if("Melvin".equals(w.getName()))
iter.remove();
}
When I run this code I get a runtime java.lang.UnsupportedOperationExceptionError with a vague exception message of null that gets thrown on the iter.remove() line. It seems that some Java Iterators don’t support the remove method and will throw this exception.
I can’t change the widgetService.getAllWidgets() method to return a List<Widget> and am stuck with the Widget[] array return value.
So I ask: what can I do to loop through my widgets array and dynamically prune out ones that are named “Melvin“?
If you can afford it, just make a mutable copy of the list. Replace
with