I have a public Set<ProjectItem> projectItems = new HashSet<ProjectItem>(); which can contains two types of classes (ProjectItem is a abstract super class for both of them). The classes are Deliverable and Task. I want get all objects of the class Deliverable from the Set. Therefore I write this:
public Set<Deliverable> allDeliverables(){ Set<Deliverable> result = new HashSet<Deliverable>(); for(Iterator<ProjectItem> iter = projectItems.iterator(); iter.hasNext(); iter.next()){ if (iter.next().getClass() == Deliverable.class){ Deliverable del = (Deliverable) iter.next(); result.add(del); } } return result; }
But this makes an exception -
Exception in thread "main" java.lang.ClassCastException: edu.Chryb.ProjectManagement.Task cannot be cast to edu.Chryb.ProjectManagement.Deliverable
in the Line with: Deliverable del = (Deliverable) iter.next();
Is something in the if query wrong?
Thanks for every help.