BrownTownCoder
BrownTownCoder

Reputation: 1372

Add identical objects to a Set<E>

How do I make my code to add identical objects to a SET? I guess I will have to do something with hashcode() or equal() functions.

Class Order {

private id;
private Set<Discount>;

} 

Class Discount {

private id;
private Long amount;
}

Now if I try to save two discounts of $1 each, the SET only shows one discount. When hibernate saves it, discounts will have different IDs, but they are same as of now. Don;t want to change the definition of Order class, as it's a big project and changes will be endless

Upvotes: 0

Views: 104

Answers (2)

holtc
holtc

Reputation: 1820

You cannot add identical objects to a set, because that is the point of a set. A set contains unique elements. You would be better off using a list or a map.

Upvotes: 0

Brandon McKenzie
Brandon McKenzie

Reputation: 1685

According to the JavaDoc for the Set interface, a set is not allowed to contain duplicate identical elements (as defined by equals and hashcode). While this will work fine when hibernate saves the discounts (since you said the ids will be different), the ids are the same right now, so what you are trying to accomplish is not possible without doing things that future people who will be stuck maintaining your code will hate you for.

Since you do not desire to change the Order class, your best recourse is to retroactively change the ids on your discounts to be unique.

Upvotes: 1

Related Questions