添加集合中的元素

时间:2011-03-18 18:43:41

标签: java hashset

我必须与一些本科生和研究生一起创建课程,然后使用方法getPostgraduates()从课程中提取所有以“Ismael Bento”为主管的研究生,并使用类Notifier向他们发送消息(打印)文本和收件人)。 但是,没有任何内容被打印出来......我的猜测是我的getPostgraduates()方法有问题。

这是主要方法:

package students;

import java.util.*;

public class ProgrammingTest {

    public static void main (String[] args){
        Academic rr = new Academic("Ricardo Rodriguez");
        Academic ib = new Academic("Ismael Bento");
        Set<Student> students = new HashSet<Student>();

        Undergraduate ug1 = new Undergraduate("gg4", "Greg","gg4@", rr);
        Undergraduate ug2 = new Undergraduate("pr3", "Pete","pr3@", ib);
        Postgraduate pg1 = new Postgraduate("te2", "Ted", "te2@", rr);
        Postgraduate pg2 = new Postgraduate("yj34", "Yao", "yj34@", ib);
        Postgraduate pg3 = new Postgraduate("jj8", "Jack", "jj8@", ib);

        students.add(ug1);
        students.add(ug2);
        students.add(pg1);
        students.add(pg2);
        students.add(pg3);

        Course c1 = new Course("c1", students);
        Set<? extends Notifiable> n = c1.getPostgraduates("Ismael Bento");
        Notifier notifier = new Notifier(n);
        notifier.doNotifyAll("You have been notified!");

    }

}

和课程班:

package students;

import java.util.*;

public class Course {

    private Set<Student> students;
    private String name;

    public Course (String name, Set<Student> students){
        this.name = name;
        this.students = students;
    }

    public Set<Postgraduate> getPostgraduates(String nameOfSupervisor){
        Set<Postgraduate> postgraduates = new HashSet<Postgraduate>();

    for(Postgraduate p : postgraduates) {  
        if (p.getSupervisor().equals(nameOfSupervisor)){
            postgraduates.add(p);
        }
    }
        return postgraduates;

    }

}

和通知程序类:

package students;
import java.util.Iterator;
import java.util.Set;

public class Notifier {
    Set<? extends Notifiable> notifiables;

    public Notifier (Set<? extends Notifiable> n) {
        notifiables = n;
    }

    public void doNotifyAll(String message) {

        Iterator<? extends Notifiable> i = notifiables.iterator();
        while(i.hasNext()){
            i.next().notify();
        }


    }
}

3 个答案:

答案 0 :(得分:7)

问题确实在getPostgraduates()。这样做的原因是您只能与使用空值初始化的对象postgraduate进行比较。您应该贯穿整个学生群体,并与您正在寻找的主管一起检查研究生。

答案 1 :(得分:2)

您正在通过==符号比较对象并使用此条件来决定是否添加set ..这将始终为false,因为它比较引用而不是实际对象..如果您想要比较对象,则覆盖等于

if(postgraduate.getSupervisor() == new Academic(nameOfSupervisor)){
                postgraduates.add(postgraduate);
}

如果你想比较对象,那么你应该调用equals并覆盖equals。
HashSet实现还依赖于equals和hashcode来确定相等性。你是否重写了研究生中的equals和hashcode?

答案 2 :(得分:1)

if(postgraduate.getSupervisor() == new Academic(nameOfSupervisor))

这永远不会成真。

您正在比较对象(出于所有实际目的,对象引用指向的内存地址),而不是对象的内容。

您没有列出PostgraduateAcademic课程的代码,所以从那时起您就自己了:)

编辑:我搜索了家庭作业。看起来PostgraduateAcademic都是Person,其getName()方法。