F
F
FlaIDzeres2014-02-16 14:49:24
Java
FlaIDzeres, 2014-02-16 14:49:24

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;
    }

Main class
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

1 answer(s)
T
tsegorah, 2014-02-16
@tsegorah

Try to use ListIterator , it supports delete operation, but with limitations, I recommend reading javadoc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question