HashSet collection is based on HashMap . In both cases, for the contains() method and add() , it iterates through the elements of the collection. For HashSet / HashMap , in general, these are fast operations that are performed in O(1) , i.e. for constant time. The article in the topic .
However, unnecessary traversal of the collection can be avoided by deleting the contains() method since the add (E) method and so checks for the presence of an element and returns a boolean:
if ( !a.add(object) ) { throw new IllegalArgumentException("..."); } return object;
Also, I would think whether it is necessary to return anything from the method at all. From the above code, it makes no sense to return a reference to an object that is passed to the method as an argument. If the element is not added, RuntimeException , that is enough.
In general, the usual code, without an explicit code smell. By one method it is not always possible to judge the effectiveness of the algorithm. If you need an expedition in this place - throw an expection. This is determined only by the logic of your application.