Modify the Course class (posted below) so that it implements the Comparable inte
ID: 664094 • Letter: M
Question
Modify the Course class (posted below) so that it implements the Comparable interface (from the java.lang package). Order the courses first by department and then by course number. Then write a program that uses an ordered list to maintain a list of courses.
This program must demonstrate that your newly written Course.compareTo() method works correctly.
You canNOT use a built-in Java data structure for the ordered list. You can use either an ArrayList<Course> implementation or a LinkedList<Course> implementation, but be sure to include implementation .java files like those in the text.
Course Class:
Explanation / Answer
import java.io.Serializable;
import java.io.*;
import java.util.*;
public class Course implements Comparable<Course>, Serializable {
String prefix;
int number;//Declaring integer
String Department;//Department for students
String grade;//Grades in string
public Course(String prefix, int number, String Department, String grade)
{
this.prefix = prefix;
this.number = number;
this.Department = Department;
if (grade == null)
this.grade = "";
else
this.grade = grade;
}
public Course(String prefix, int number, String Department)
{
this(prefix, number, Department, "");
}
public String getPrefix()
{
return prefix;
}
public int getNumber()
{
return number;
}
public String getDepartment()
{
return Department;
}
public String getGrade()
{
return grade;
}
public void setGrade(String grade)
{
this.grade = grade;
}
public boolean taken()
{
return !grade.equals("");
}
public boolean equals(Object other)
{
boolean result = false;
if (other instanceof Course)
{
Course otherCourse = (Course) other;
if (prefix.equals(otherCourse.getPrefix()) &&
number == otherCourse.getNumber())
result = true;
}
return result;
}
//The compareTo function:
public int compareTo(Course o)
{
if(getDepartment().equals(o.getDepartment()))
{
return 0;
}
else if()
{
return -1;
}
else
{
return 1;
}
}
public String toString()
{
String result = prefix + " " + number + ": " + Department;
if (!grade.equals(""))
result += " [" + grade + "]";
return result;
}
}
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import java.*;
public class stackCourse//Class Name declaration
{
public static void main(String[] args) //courses
{
Course a = new Course("CSE", 350, "Engineering");
Course b = new Course("AERONAUTICAL", 750, "AERO");
Course c = new Course("MECH", 250, "MECH");
Course d = new Course("BIO", 504, "MEDICAL");
Course e = new Course("NANO", 814, "TECHNOLOGY");
Course f = new Course("CHEMICAL", 920, "Chemical");
Course[] courses = {p,q,r,s,t,u};//Couse name declaration
for(int m=0; m<courses.length; m++)
System.out.println(courses[m].getDepartment());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.