How to remove items from a list

1

I have a class that creates circles every time I touch the screen and when it meets a certain condition I want to eliminate them from the list. How can I do? Thank you.

    public class Juego extends SurfaceView implements View.OnTouchListener {


    Circulos circulos;
    Paint paint;
    int x, y;

    List<Circulos> lista_circulos = new ArrayList<Circulos>();

    public Juego(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setOnTouchListener(this);
        setFocusable(true);

        circulos = new Circulos(this);

        paint = new Paint();
    }

    public void onDraw(Canvas canvas){

        paint.setColor(Color.WHITE);
        canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paint);

        for (Circulos circulos : lista_circulos) {
            circulos.onDraw(canvas);
        }

        invalidate();
    }

    private Circulos crearCirculos() {
        return new Circulos(this);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        x = (int) motionEvent.getX();
        y = (int) motionEvent.getY();

        crearCirculo();

        invalidate();
        return false;
    }

    public void crearCirculo(){
        lista_circulos.add(crearCirculos());
    }
}
    
asked by Agustin Val 04.03.2018 в 14:11
source

2 answers

0

You can remove the items by their index in the list, to avoid ConcurrentModificationException in this case you can create a list in which you add the elements to be deleted and in the end you remove these elements from the original list.

In this case you can use this method where you can define the number of objects in your list.

private void eliminarElementos(int elementos){

    //Si el numero elementos a eliminar es mayor a la cantidad de objetos
    //en la lista, asegura eliminar todos los elementos en la lista y evita
    //IndexOutOfBoundsException
    if(listaCirculos.size()< elementos){
        elementos = listaCirculos.size();
    }

    List<Circulos> listToRemove = new ArrayList<Circulos>();
    for(int i = 0; i< elementos; i++){
        listToRemove.add(listaCirculos.get(i));
    }
    listaCirculos.removeAll(listToRemove);
}
    
answered by 05.03.2018 в 20:08
-1

If you want to eliminate taking into account the Object and not the index, you have to overwrite the method equal (Object) of your class Circles so that it returns true if it is the same object. The method arraylist.remove (Object) uses the equals method of the object you are passing, in this case a "circle" object.

@Override
public boolean equals(Circulo obj) {
    return (this.radio.equals(((User) obj).radio) && (this.diametro
            .equals(((User) obj).diametro)));
}

then to remove

listaCirculos.remove(new Circulo("10","15"));
    
answered by 04.03.2018 в 21:02