You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.


Step 1: Update the 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 + "}";
    }
}

Step 2: Implement the 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;
    }
}

Step 3: Update 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();
    }
}

Alternative: Use 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);

Key Tips
  • Ensure Pet has getters for all properties—you'll need them for sorting and lookup.
  • If pet names aren't unique, adjust the position method 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 +1 in the position method.

内容的提问来源于stack exchange,提问作者PaperHat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:44:45