使用Comparable<T>接口、compareTo()与ArrayList的Java作业疑问
Hey there! Let's work through this Java homework problem step by step. I'll cover how to properly implement the Comparable interface, use compareTo() in your test class, and integrate ArrayList along with those required output statements.
First: Make sure your homework classes correctly implement Comparable
Since all your classes (MyMath3, MyEnglish3, etc.) have the same structure, let's use MyMath3 as an example—you can copy this pattern for the others, just update the homework type string.
public class MyMath3 implements Comparable<MyMath3> { // Assume we're comparing a score value (adjust this to your actual numeric field) private int homeworkScore; private String homeworkType = "math"; // Constructor to initialize the score public MyMath3(int score) { this.homeworkScore = score; } // Implement the compareTo method required by Comparable @Override public int compareTo(MyMath3 otherMathHomework) { // Use Integer.compare for clean integer comparison logic // Returns 0 if scores are equal, positive if this score is higher, negative otherwise return Integer.compare(this.homeworkScore, otherMathHomework.homeworkScore); } // Method to print the required homework statement public void printHomeworkDetails() { System.out.println("Homework for " + homeworkType + "..."); } // Getter if you need to access the score in your test class public int getHomeworkScore() { return homeworkScore; } }
For MyEnglish3, MyScience3, and MyJava3, just swap the homeworkType value (e.g., "english", "science")—the rest of the code stays identical.
Second: Build your test class with ArrayList and call compareTo()
Here's how you can set up a test class to store homework objects in an ArrayList, compare them using compareTo(), and print those required statements:
import java.util.ArrayList; public class HomeworkTest { public static void main(String[] args) { // 1. Create an ArrayList to store MyMath3 objects ArrayList<MyMath3> mathHomeworks = new ArrayList<>(); mathHomeworks.add(new MyMath3(90)); mathHomeworks.add(new MyMath3(85)); mathHomeworks.add(new MyMath3(90)); // 2. Compare objects using compareTo() MyMath3 firstMathHomework = mathHomeworks.get(0); for (int i = 1; i < mathHomeworks.size(); i++) { MyMath3 currentMathHomework = mathHomeworks.get(i); // Call compareTo() to check if scores are equal if (firstMathHomework.compareTo(currentMathHomework) == 0) { System.out.printf("Math homework %d and %d have equal scores (%d)%n", 0, i, firstMathHomework.getHomeworkScore()); } else { System.out.printf("Math homework %d and %d have different scores%n", 0, i); } // Print the required homework statement currentMathHomework.printHomeworkDetails(); } // 3. Handle multiple types of homework (optional, if you want a single ArrayList) ArrayList<Object> allHomeworks = new ArrayList<>(); allHomeworks.add(new MyEnglish3(88)); allHomeworks.add(new MyScience3(92)); allHomeworks.add(new MyJava3(85)); // Print details for all homework types for (Object homework : allHomeworks) { if (homework instanceof MyEnglish3) { ((MyEnglish3) homework).printHomeworkDetails(); } else if (homework instanceof MyScience3) { ((MyScience3) homework).printHomeworkDetails(); } else if (homework instanceof MyJava3) { ((MyJava3) homework).printHomeworkDetails(); } } // Quick example comparing two same-type objects directly MyScience3 scienceHW1 = new MyScience3(75); MyScience3 scienceHW2 = new MyScience3(75); if (scienceHW1.compareTo(scienceHW2) == 0) { System.out.println("These two science homeworks have equal scores!"); } } }
Key Notes to Remember:
- When implementing
Comparable, always specify the generic type (likeComparable<MyMath3>) so you don't have to cast objects incompareTo(). - A return value of
0fromcompareTo()means the two objects are considered equal based on your comparison logic (here, equal scores). - If your numeric field is a
doubleinstead ofint, useDouble.compare(this.value, other.value)in thecompareTo()method. - If you want to avoid the
instanceofchecks for mixed homework types, you could create an abstract parent class (e.g.,Homework) that all your classes inherit from—this would let you useArrayList<Homework>instead ofArrayList<Object>for cleaner code.
内容的提问来源于stack exchange,提问作者Mi Le

