doc about java.util.Set.contains(Object o) says:
Returns true if and only if this collection contains an element e such that (o == null? E == null: o.equals (e)).
However, there is a POJO here (as you can see, I rewrote its equals method):
public class MonthAndDay { private int month; private int day; public MonthAndDay(int month, int day) { this.month = month; this.day = day; } @Override public boolean equals(Object obj) { MonthAndDay monthAndDay = (MonthAndDay) obj; return monthAndDay.month == month && monthAndDay.day == day; } }
So please, why does the following code print false instead of true ?
Set<MonthAndDay> set = new HashSet<MonthAndDay>(); set.add(new MonthAndDay(5, 1)); System.out.println(set.contains(new MonthAndDay(5, 1)));
The solution is to rewrite the contains(Object o) method, but the original one should be (almost) exactly the same, am I mistaken?
Set<MonthAndDay> set = new HashSet<MonthAndDay>() { private static final long serialVersionUID = 1L; @Override public boolean contains(Object obj) { MonthAndDay monthAndDay = (MonthAndDay) obj; for (MonthAndDay mad : this) { if (mad.equals(monthAndDay)) { return true; } } return false; } }; set.add(new MonthAndDay(5, 1)); System.out.println(set.contains(new MonthAndDay(5, 1)));
sp00m source share