What I am about to suggest has nothing to do with ClassCastException, which is thrown simply because you are checking contains
with an int
argument on a set of objects of type Person
... short answer: you can't cast an object to a subclass of which it is not an instance. Even the javadoc says exactly that.
For situations like this, I really like to use Guava predicates. A predicate allows you to apply a boolean condition to any iterable, returning those elements that satisfy the specified condition. In your example, you can define predicates that return the subset of people of whatever age you want.
Predicate<Person> getAgePredicate(final int age) {
return new Predicate<Person>() {
public boolean apply(Person p) { return p.age == age; }
};
}
Set<Person> people = new Hashset<>();
... // populate people
Set<Person> peopleOfAgeTwelve = Sets.filter(people, getAgePredicate(12));
Hope this helps.