I am stuck on the following question:
我坚持以下问题:
Study the following Java class header and code fragment:
研究以下Java类头和代码片段:
class ExamScript implements Comparable<ExamScript> { private String studentName; private int mark; ...rest of class... /** * Compares this object with the specified object for e *@param e the object to be compared *@return -1 if object is less than the specified object *@return 0 if object is equal to the specfied object **/ public int compareTo(ExamScript e) { if (mark < e.mark) return - 1; if (mark == e.mark) return 0; return 1; } }
Give suitable documentation for the
compareTo
method. In particular state the meaning of the values returned from this method.为compareTo方法提供合适的文档。特别声明了从此方法返回的值的含义。
Write the code for the
compareTo
method according to your specification.根据您的规范编写compareTo方法的代码。
I've documented and written the code as shown above. Can anyone confirm for me if I can improve my documentation/coding a bit or if that is fine the way it is?
我已经记录并编写了如上所示的代码。任何人都可以向我确认,如果我可以改善我的文档/编码或者如果它的方式很好吗?
2 个解决方案
#1
1
Make sure to add @returns 1 if e is greater than this object.
如果e大于此对象,请确保添加@returns 1。
You can be more specific with your @returns. Try using the format I used above. Also, if it's not apparent from reading the code, try to explain what mark is, and why it's being used to compare.
您可以使用@returns更具体。尝试使用我上面使用的格式。此外,如果通过阅读代码不明显,请尝试解释什么是标记,以及为什么它用于比较。
Check Oracle's standards for more information.
查看Oracle的标准以获取更多信息。
#2
1
the problem I see it that when the grades are equal the student are considered equal (at least when algorithms assume a.compareTo(b)==0
implies a.equals(b)
depending on your use this might be a good thing
问题我认为当等级相等时,学生被认为是相等的(至少当算法假设a.compareTo(b)== 0意味着a.equals(b)取决于你的使用,这可能是一件好事
but if it's bad you can fix this by comparing the names instead of returning 0
但如果它很糟糕你可以通过比较名称而不是返回0来解决这个问题
public int compareTo(ExamScript e)
{
if (mark < e.mark)
return - 1;
if (mark == e.mark)
return studentName.compareTo(e.studentName);
return 1;
}
#1
1
Make sure to add @returns 1 if e is greater than this object.
如果e大于此对象,请确保添加@returns 1。
You can be more specific with your @returns. Try using the format I used above. Also, if it's not apparent from reading the code, try to explain what mark is, and why it's being used to compare.
您可以使用@returns更具体。尝试使用我上面使用的格式。此外,如果通过阅读代码不明显,请尝试解释什么是标记,以及为什么它用于比较。
Check Oracle's standards for more information.
查看Oracle的标准以获取更多信息。
#2
1
the problem I see it that when the grades are equal the student are considered equal (at least when algorithms assume a.compareTo(b)==0
implies a.equals(b)
depending on your use this might be a good thing
问题我认为当等级相等时,学生被认为是相等的(至少当算法假设a.compareTo(b)== 0意味着a.equals(b)取决于你的使用,这可能是一件好事
but if it's bad you can fix this by comparing the names instead of returning 0
但如果它很糟糕你可以通过比较名称而不是返回0来解决这个问题
public int compareTo(ExamScript e)
{
if (mark < e.mark)
return - 1;
if (mark == e.mark)
return studentName.compareTo(e.studentName);
return 1;
}