I can not override the add methods. Rather, I can, but they do not work as they should. The essence of the problem: There are figures (like Figure) and a box (ArrayList <> ()). The figures we add to the box. You cannot add the same shape to the box. Trying to redefine this in class with my box - does not 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 class Main you can still easily add 2 identical figures to the box. What is wrong with my 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 performing see: true true 2
A should be: true false 1
Box
from anArrayList
explicitly defined in a task? - Sergey Gornostaev