pkdrillancl79
pkdrillancl79

Reputation: 11

I have an attribute for a specific class and want to return the whole object

I searched through an arraylist of Sale objects in order to find the highest sale vale which is one of the attributes. I now have the highest sale value but I want to return the whole object that has the highest sale rather than just the vale.

import java.util.ArrayList;
import java.util.List;

public class Branch extends Sale{
    private String localBranch;
    private ArrayList<Sale> salesList;

    public Branch(){}

    public Branch(String localBranch){
        this.localBranch = localBranch;
        salesList = new ArrayList<>();
    }

This is the constructor for the branch class that contains the method to get the highest sale class

public class Sale {
    private String houseNumber;
    private String postcode;
    private double value;
    private String monthSold;
    private int yearSold;

    public Sale(String houseNumber, String postcode, double value, String monthSold, int yearSold){
        this.houseNumber = houseNumber;
        this.postcode = postcode;
        this.value = value;
        this.monthSold = monthSold;
        this.yearSold = yearSold;
    }

This is te constructor for the Sale class

    public double getHighestSale(Branch branch){
        double highestSale = 0;
        for (int i = 0; i<salesList.size(); i++){
            if (branch.getSalesList().get(i).getValue()> highestSale){
                highestSale = branch.getSalesList().get(i).getValue();
            }
        }
        return highestSale;
    }

This is the code I have so far, I want to return the Sale class with highestSale as an attribute rather than highestSale

Upvotes: 1

Views: 577

Answers (1)

Anastasia
Anastasia

Reputation: 802

public Sale getHighestSale(Branch branch){
        Sale highestSale = null;
        for (int i = 0; i<salesList.size(); i++){
            if (branch.getSalesList().get(i).getValue() > highestSale.getValue()){
                highestSale = branch.getSalesList().get(i);
            }
        }
        return highestSale;
    }

Something like this. You need to add a few changes to the getHighestSale function. Instead of tracking the greatest sale value, you track the Sale itself.

Upvotes: 1

Related Questions