Java多类场景下数组对象比较求助:按重量与身高排序
Hey there! Let's break down how to solve this problem properly—we'll cover sorting with both Comparable and Comparator, plus get the position lookup and string-to-pet conversion working smoothly.
Pet Class with Sorting Logic First, we'll give Pet a natural ordering by implementing the Comparable interface. This lets us define exactly how pets should be sorted: first by weight (lightest to heaviest), then by a weight-height relationship (we'll use height ascending as the default, but I'll show you how to adjust this).
public class Pet implements Comparable<Pet> { private String name; private int weight; private int height; // Constructor public Pet(String name, int weight, int height) { this.name = name; this.weight = weight; this.height = height; } // Getters (critical for sorting and lookup) public String getName() { return name; } public int getWeight() { return weight; } public int getHeight() { return height; } // Define sorting logic @Override public int compareTo(Pet otherPet) { // First compare weight (ascending order) int weightComparison = Integer.compare(this.weight, otherPet.weight); if (weightComparison != 0) { return weightComparison; } // If weights are equal, sort by height (ascending) // Want a different weight-height relationship? Swap this with: // double thisRatio = (double) this.weight / this.height; // double otherRatio = (double) otherPet.weight / otherPet.height; // return Double.compare(thisRatio, otherRatio); return Integer.compare(this.height, otherPet.height); } // Optional: For easier debugging/output @Override public String toString() { return "Pet{name='" + name + "', weight=" + weight + ", height=" + height + "}"; } }
Pets Class This class will handle storing the sorted pet array, finding a pet's position, and converting user input strings to a Pet object.
import java.util.Arrays; import java.util.Optional; public class Pets { private Pet[] sortedPets; // Constructor: Takes a pet array, makes a copy, then sorts it public Pets(Pet[] pets) { this.sortedPets = Arrays.copyOf(pets, pets.length); Arrays.sort(this.sortedPets); // Uses Pet's compareTo method } // Return 1-based position of the target pet (users expect positions to start at 1) public int position(Pet targetPet) { for (int i = 0; i < sortedPets.length; i++) { // Match by name (adjust if names aren't unique—add weight/height checks) if (sortedPets[i].getName().equals(targetPet.getName())) { return i + 1; } } return -1; // Pet not found } // Find a Pet by name (case-insensitive for user-friendliness) public Pet getPetFromString(String inputName) { Optional<Pet> foundPet = Arrays.stream(sortedPets) .filter(pet -> pet.getName().equalsIgnoreCase(inputName.trim())) .findFirst(); return foundPet.orElse(null); // Return null if no match } // Optional: Getter to verify sorted order for debugging public Pet[] getSortedPets() { return sortedPets; } }
PetActions for User Interaction Now we'll tie it all together in the main method—create pets, sort them, and let users query positions.
import java.util.Scanner; public class PetActions { public static void main(String[] args) { // Create 5 sample pets Pet[] pets = { new Pet("Buddy", 10, 30), new Pet("Mittens", 8, 25), new Pet("Max", 10, 28), new Pet("Luna", 8, 22), new Pet("Charlie", 12, 35) }; // Instantiate Pets (sorts the array automatically) Pets petCollection = new Pets(pets); // Optional: Print sorted list to verify System.out.println("Sorted Pets (Lightest to Heaviest):"); for (Pet pet : petCollection.getSortedPets()) { System.out.println(pet); } // Get user input to find a pet's position Scanner scanner = new Scanner(System.in); System.out.print("\nEnter a pet's name to find its position: "); String userInput = scanner.nextLine(); // Look up the pet and get its position Pet targetPet = petCollection.getPetFromString(userInput); if (targetPet != null) { int petPosition = petCollection.position(targetPet); System.out.printf("'%s' is at position %d%n", targetPet.getName(), petPosition); } else { System.out.printf("No pet found with the name '%s'%n", userInput); } scanner.close(); } }
Comparator for Flexible Sorting If you don't want to lock Pet into a single sorting logic, use a Comparator instead of Comparable. Modify the Pets constructor to accept a comparator:
// Updated Pets constructor public Pets(Pet[] pets, Comparator<Pet> comparator) { this.sortedPets = Arrays.copyOf(pets, pets.length); Arrays.sort(this.sortedPets, comparator); }
Then in PetActions, define your sorting logic on the fly:
Comparator<Pet> petComparator = (p1, p2) -> { int weightComp = Integer.compare(p1.getWeight(), p2.getWeight()); if (weightComp != 0) return weightComp; // Custom weight-height logic here return Integer.compare(p1.getHeight(), p2.getHeight()); }; Pets petCollection = new Pets(pets, petComparator);
- Ensure
Pethas getters for all properties—you'll need them for sorting and lookup. - If pet names aren't unique, adjust the
positionmethod to compare weight and height alongside the name to avoid false matches. - The position is 1-based (standard for user-facing interfaces), but you can switch to 0-based by removing the
+1in thepositionmethod.
内容的提问来源于stack exchange,提问作者PaperHat

