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

  • Is the requirement to inherit Box from an ArrayList explicitly defined in a task? - Sergey Gornostaev
  • @SergeyGornostaev is not, this is not written in the task. Written just what should be "able" box. And then I namudril myself already)) - Vladislav Estrin
  • 2
    So ArrayList already has an internal storage, you add to it just through super, but for some reason you have created a List box and check for the presence of elements in it, and not where you add it. Delete it and write this instead of box. And in general, if only unique elements are needed, then why not use Set? - Drawn Raccoon
  • @DrawnRaccoon it will sound ridiculous, but we have not passed it yet)))) Your decision helped. Thank. I did not understand the essence itself apparently - Vladislav Estrin

1 answer 1

First of all

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

Secondly, not ArrayList better, but HashSet .

Thirdly, it is necessary to implement the hash and equals methods in the Figure class.

  • Thank you, I did just that. Tell me, is it possible to do without inheriting from ArrayList (just create a sheet in the class and register the methods we need) and is there any point in this? PS By the way, in the class declaration you can simply write ArrayList {the result is the same @SergeyGornostaev - Vladislav Estrin
  • @ VladislavEstrin of course is possible and it even makes sense. - Sergey Gornostaev
  • I probably will do so) thanks a lot for your help. equals and hash I redefined) - Vladislav Estrin