I am doing an assignment that requires me to use the Comparable interface and use compareTo() to see if two numbers are equal. I am also required to use an ArrayList but I don't understand how to execute the compareTo() in the test class. This is my code so far.
public abstract class Homework3 implements Comparable<Homework3>
{
// instance variables
public int pagesRead;
public String typeHomework;
public Homework3()
{
pagesRead = 0;
typeHomework = "none";
}
public int getPagesRead()
{
return pagesRead;
}
public void setPagesRead(int p)
{
pagesRead = p;
}
public String getTypeHomework()
{
return typeHomework;
}
public void setTypeHomework(String t)
{
typeHomework = t;
}
public abstract void createAssignment(int p);
public int compareTo(Homework3 p)
{
if (pagesRead < p.pagesRead)
{
return -1;
}
else if (pagesRead == p.pagesRead)
{
return 0;
}
else
{
return 1;
}
}
}
public class MyMath3 extends Homework3
{
public MyMath3()
{
super();
}
public void createAssignment(int p)
{
pagesRead = p;
typeHomework = "Math";
}
public String toString()
{
return typeHomework + " - must read " + pagesRead + " pages.";
}
}
There are 3 more classes called MyEnglish3, MyScience3, and MyJava3 but there are basically the same as the math class. The only thing that changes is the type of homework. I'm trying to print out a statement that says "Homework for math and english have the same number of pages" as the last line after printing the amount of pages for each homework (Math, Science, English, Java). I have to use compareTo() but I really don't know how I can compare the page numbers of each object in the arraylist. This is my test class.
public class TestHomework3
{
public static void main(String [] args)
{
List<Homework3> test = new ArrayList<Homework3>();
test.add(new MyMath3());
test.add(new MyScience3());
test.add(new MyEnglish3());
test.add(new MyJava3());
for (Homework3 p : test)
{
if (p instanceof MyMath3)
{
p.createAssignment(4);
}
else if (p instanceof MyScience3)
{
p.createAssignment(6);
}
else if (p instanceof MyEnglish3)
{
p.createAssignment(4);
}
else if (p instanceof MyJava3)
{
p.createAssignment(5);
}
System.out.println(p);
}
}
}
Should I change the for each loop? Or is there another way that I can compare the page number of each type of homework while still using the arraylist and the Comparable interface?