string - Java compareTo method. The student.compareTo method should return -
i ask write student.compareto method should return 0 if first name of 2 students , last name of 2 students same. should return negative value if student's name sort lexicographically lower 1 passed in. should return positive value if student's name sort lexicographically higher 1 passed in.
here code far. negative value , positive value should fixed value or should use compareto value?
public int compareto(student){ int comparison = (this.firstname.compareto(student.firstname)); int comparison2 = (this.lastname.compareto(student.lastname)); if (comparison == comparison2) return 0; else if ((comparison=0 && comparison2<0) ||(comparison<0 && comparison2=0) return -1; else return 1; }
this code. wondering if did correctly
public int compareto(student){ string studentinfo=(this.firstname + this.lastname); string studentinfo2=(s1.firstname + s1.lastname); int comparison =studentinfo.compareto(studentinfo2); return comparison; }
this complicated...
chain comparisons; if first 1 returns 0, run second; if second returns 0, run third; etc.
that is, return first comparison result non zero, or last one. example:
@override public int compareto(final student other) { int ret = firstname.compareto(other.firstname); if (ret != 0) // no need go further return ret; // hypothetic second comparison before lastname // ret = foo.compareto(other.foo); // if (ret != 0) // return ret; // rinse, repeat... // previous comparisons returned 0, // return result of last comparison return lastname.compareto(other.lastname); }
guava has nice utility class that:
@override public int compareto(final student other) { return comparisonchain.start() .compare(firstname, other.firstname) .compare(lastname, other.lastname) .result(); }
Comments
Post a Comment