Finding a min/max in an array or ArrayList of objects requires deciding what to store. Options include:

Consider the Bunny class below.

public class Bunny
{
    private double weight;
    private int fluffiness;
    
    public Bunny(double weight, int fluffiness)
    {
        this.weight = weight;
        this.fluffiness = fluffiness;
    }
    
    public double getWeight()
    {
        return weight;
    }
    
    public int getFluffiness()
    {
        return fluffiness;
    }
}

Method getWeightOfFluffiest returns the weight of the fluffiest bunny in its parameter bunnies.

Option 1: Store an index

public static double getWeightOfFluffiest(Bunny[] bunnies)
{
    int indexOfFluffiest = 0;
    
    for(int i = 1; i < bunnies.length; i++)
    {
        if(bunnies[i].getFluffiness() > bunnies[indexOfFluffiest].getFluffiness())
            indexOfFluffiest = i;
    }
    
    return bunnies[indexOfFluffiest].getWeight();
}

This implementation stores the index of the fluffiest bunny. This provides sufficient information to identify whether the bunny at i is fluffier than the fluffiest bunny so far. It also provides sufficient information to return the desired attribute (the weight) once the fluffiest bunny has been identified.

Storing an index provides lots of flexibility. It is possible to return (or use) the index itself, the value at the index, or something about the value.

Option 2: Store a reference to an object

public static double getWeightOfFluffiest(Bunny[] bunnies)
{
    Bunny fluffiest = bunnies[0];
    
    for(int i = 1; i < bunnies.length; i++)
    {
        if(bunnies[i].getFluffiness() > fluffiest.getFluffiness())
            fluffiest = bunnies[i];
    }
    
    return fluffiest.getWeight();
}

This implementation stores a reference to the fluffiest Bunny object. This provides sufficient information for both the comparison and the return.

Option 3: Store attributes

public static double getWeightOfFluffiest3(Bunny[] bunnies)
{
    int maxFluffiness = bunnies[0].getFluffiness();
    double weightOfFluffiest = bunnies[0].getWeight();
    
    for(int i = 1; i < bunnies.length; i++)
    {
        if(bunnies[i].getFluffiness() > maxFluffiness)
        {
            maxFluffiness = bunnies[i].getFluffiness();
            weightOfFluffiest = bunnies[i].getWeight();
        }
    }
    
    return weightOfFluffiest;
}

This implementation stores the fluffiness of the fluffiest bunny so far, as well as the weight of that bunny. It is NOT sufficient to store just one of these attributes. Storing only the fluffiness does not provide access to the weight at the end. Storing only the weight does not provide sufficient information for the comparison.

When storing attributes, it is easy to forget to update one of the attributes when a new min/max has been identified.

Comments

Comment on Finding the minimum or maximum