S
S
s2018-08-28 17:47:52
Java
s, 2018-08-28 17:47:52

Interview question: How to add two identical objects to a set?

At the interview, they asked the question: How can you make a set that adds two identical objects? or how to add two identical objects to a set?
What is the best way to do this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2018-08-28
@solovladys

The correct answer is: no way, that's why he's set.
If suddenly this is needed, then you need to use a different structure for storage. You can even call it MyMagicSet to blow someone's mosk.

S
s, 2018-08-28
@solovladys

I believe that in this case it is necessary to add an object identifier, redefine equals, in which to check the largest object id with the data we need by bucket. If id>1 then don't add. But again, the objects are identical in fields, except for id, and this is already a change in the class structure, which is not desirable.

I
Iloveski, 2018-08-29
@Iloveski

Redefine equals twice for the same object, return false, hashcode to mix in a random number. Two objects completely identical in fields are possible. Equals do not override (references to different objects). Hashcode override by mixing a random number into the calculation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question