Answer the question
In order to leave comments, you need to log in
How to implement removing an element from a Java collection?
I can't figure out what's wrong. I delete an element of the collection through an iterator (I read somewhere that it is safe deletion), but a java.lang.UnsupportedOperationException is thrown.
But an iterator from a list must support the remove() method; (the method is not completed so it doesn't matter that it always returns false)
public boolean find(List x, List y) {
List z=new LinkedList();
Object obj1;
Object obj2;
Iterator iteratorX =x.iterator();
Iterator iteratorY =y.iterator();
try {
while (iteratorX.hasNext()){
obj1=iteratorX.next();
while (iteratorY.hasNext()){
obj2=iteratorY.next();
if(obj1.equals(obj2)){
System.out.println(obj2);
z.add(obj2);
iteratorY.remove();
break;
}
else {
iteratorY.remove();
break;
}
}
}
}
catch (Exception e){
System.out.print(e.getMessage());
}
return false;
}
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
Subsequence s = new SubsequenceImpl();
boolean b = s.find(Arrays.asList("A", "B", "C", "D"),Arrays.asList("A", "ABC", "B", "M", "D", "M", "C","DC", "D"));
System.out.println(b); // Результат: true
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question