Redefining the add sheet methods

I can't override the add methods. Or rather, I can, but they don't work the way they should. The essence of the problem: We have shapes (of the Figure type) and a box (ArrayList ()). We add the shapes to the box. You can't add the same shape to a box. I try to redefine this in the class with my box - it doesn't work.

Class box:

import java.util.ArrayList;
import java.util.List;

public class Box extends ArrayList {
    private List<Figure> box;

    public Box() {
        box = new ArrayList<>();
    }

    @Override
    public boolean add(Object o) {
        if (box.contains(o)){
            return false;
        }
        return super.add(o);
    }

    @Override
    public void add(int index, Object element) {
        if (box.contains(element)){
            return;
        }
        super.add(index, element);
    }
}

As a result, from the Main class, you can still safely add 2 identical shapes to the box. What's wrong with my a box?)

Here is the Main class:

public class Main {
    public static void main(String[] args) {
        Box box = new Box();

        PaperCircle paperCircle = new PaperCircle(5);

        System.out.println(box.add(paperCircle));
        System.out.println(box.add(paperCircle));

        System.out.println(box.size());

    }
}

When executing, we see: true true 2

And it should be: true false 1

Author: Estryn Vladislav, 2019-05-03

1 answers

First

public class Box extends ArrayList<Figure> {
    @Override
    public boolean add(Figure figure) {
        if (this.contains(figure)){
            return false;
        }
        return super.add(figure);
    }
}

Secondly, it is better to use ArrayList, but HashSet.

Third, it is worth implementing in the class Figure hash and equals methods.

 2
Author: Sergey Gornostaev, 2019-05-03 09:17:28