您可以添加的能力Student
返回其标记为一组:
public class Student {
private int physics;
private int english;
private int chemistry;
public Student(int physics, int english, int chemistry) {
this.physics = physics;
this.english = english;
this.chemistry = chemistry;
}
public Set<Integer> marks() {
return new HashSet<Integer>(Arrays.asList(physics, english, chemistry));
}
}
然后,当试图确定两个学生匹配,所有你需要看到的是他们的两个标志各自的集合是否相交,如StudentMatcher
做:
public class StudentMatcher {
public boolean matches(Student student1, Student student2) {
Set<Integer> studentMarks1 = student1.marks();
Set<Integer> studentMarks2 = student2.marks();
return haveIntersection(studentMarks1, studentMarks2);
}
private boolean haveIntersection(Set<Integer> studentMarks1, Set<Integer> studentMarks2) {
return studentMarks1.removeAll(studentMarks2);
}
}
这里是一个单元测试来验证它的工作原理:
public class StudentMatcherTest {
@Test
public void matches() {
StudentMatcher matcher = new StudentMatcher();
Student student1 = new Student(34, 45, 66);
Student student2 = new Student(99, 55, 34);
Student student3 = new Student(11, 22, 33);
assertTrue("Should match", matcher.matches(student1, student2));
assertFalse("Should not match", matcher.matches(student1, student3));
}
}
还有更多的事情可以做到这一点,但我假设你的代码比你发布的代码更复杂,所以希望这足以让你走上更好的道路。
除了另一个数据结构之外,您还需要在集合中保存分数,因为您会丢失哪个分数是哪个主题的粒度。 – 2009-11-07 11:10:09
但不幸的是,我无法更改学生对象。它在一个罐子里。 – crazyTechie 2009-11-07 11:17:14
如果你不能更改Student类,请逐个添加你的标记:'aMarks.add(a.getPhysics)','aMarks.add(a.getEnglish)'...... – 2009-11-07 11:24:10