This is my course class. Can someone please explain what the equals method is for and also the compareTo method is for in general and then explain what the methods are doing in this class.
public class Course {
private boolean isGraduateCourse;
private int courseNum;
private String courseDept;
private int numCredits;
public Course(boolean isGraduateCourse, int courseNum,
String courseDept, int numCredits) {
this.isGraduateCourse=isGraduateCourse;
this.courseNum=courseNum;
this.courseDept=courseDept;
this.numCredits=numCredits;
}
public boolean isGraduateCourse() {
return this.isGraduateCourse;
}
public int getCourseNum() {
return courseNum;
}
public String getCourseDept() {
return courseDept;
}
public int getNumCredits() {
return numCredits;
}
public String getCourseName() {
if (this.isGraduateCourse == true)
{
return "G" +
this.courseDept + this.courseNum;
}
else {
return "U" +
this.courseDept + this.courseNum;
}
}
public boolean equals(Object obj) {
Course other=(Course)obj;
if(this.isGraduateCourse!=other.isGraduateCourse) {
return
false;
}
if(this.courseNum!=other.courseNum)
{
return
false;
}
if(this.courseDept!=other.courseDept) {
return
false;
}
if(this.numCredits!=other.numCredits) {
return
false;
}
else
return
true;
}
public String toString() {
if(isGraduateCourse) {
return
String.format("Course: %3s-%3d | Number of Credits: %02d |
Graduate", courseDept,courseNum, numCredits,
isGraduateCourse);
}
else {
return
String.format("Course: %3s-%3d | Number of Credits: %02d |
Undergraduate", courseDept,
courseNum,numCredits,isGraduateCourse);
}
}
public int compareTo(Course c) {
if(courseNum==c.getCourseNum())
{
return 0;
}
else
if(courseNum>=c.getCourseNum()){
return 1;
}
else {
return -1;
}
}
}
Here equal method is used to check the equality with other
Course object
so here are checking if both objects courseNum and courseDept
and
numCredits are same than we are returning true means both
objectsare same
this will help when we are adding the Course objects to any
collections
compareTo():
This is used to compare the 2 objects to check which one is
greaters
if both are equal than it will return 0 , if it is less than than
it will return -1
else it will return 1
so here we are comparing the 2 objects based on the courseNum
so this will help when we want sort the Course objects in Arrays or Collections
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME
IT IS VERY IMP FOR ME
Get Answers For Free
Most questions answered within 1 hours.