所以我正在研究一种方法,我有点困惑,重点是将学生分成一个基于id号码的列表,以便id值较低的学生先来等等...我很困惑什么一旦我检查它是否更大,在我的if语句内做。
我现在的代码是
public boolean insort(StudentIF s) {
StudentLLNode curr = head;
if (s == null) {
return false;
}
if (head == null) {
StudentLLNode student = new StudentLLNode(s);
head = student;
size++;
//System.out.println("working");
return true;
} else {
if (curr.getStd().compareTo(s) == 0) {
//System.out.println("working");
return false;
}
while (curr.getNext() != null) {
if(s.compareTo(curr.getStd()) == 1){
//confused here
}
curr = curr.getNext();
}
//confused here
StudentLLNode student1 = new StudentLLNode(s);
curr.setNext(student1);
size++;
return true;
}
}
我与方法的比较是
public int compareTo(StudentIF other) {
if (other == null) {
return 1;
} // satisfies null student
if (this.id > other.getId())
return 1;
else if (this.id < other.getId())
return -1;
else
return 0; // if it's neither smaller nor larger, it must be equal
}
答案 0 :(得分:0)
int index = Collections.binarySearch(myStudentList, studentObject);
myStudentList.add(index < 0 ? -1 * (index + 1) : index, studentObject);
/* OR
if(index < 0)
myStudentList.add(-1 * (index + 1), studentObject);
If you did not want to add duplicates
*/
二进制搜索返回studentObject的索引,如果对象不在列表中,则返回-(insertIndex) - 1
。