您可以添加的能力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