Search code examples
javaobject-comparison

Java find the largest attribute between different objects of the same class


I'm trying to find which warehouse has the greatest number of each part. I set up a super class defined below.

 public abstract class warehouse {
    int part1;
    int part2;
    int part3;
    int part4;
    int part5;
    String name;
    File inventory = new File("Inventory.txt");
    File transactions = new File("Transactions.txt");
    public warehouse() throws FileNotFoundException {

    }

    public int getPart1() {
        return part1;
    }
    public int getPart2(){
        return part2;
    }
    public int getPart3() {
        return part3;
    }
    public int getPart4() {
        return part4;
    }
    public int getPart5() {
        return part5;
    }

I have six subclasses, I'll show the definition of one, they're all the same except for the name field.

import java.io.FileNotFoundException;
public class Atlanta extends warehouse {

    public Atlanta() throws FileNotFoundException {
        name = "Atlanta";
    }
}

I am trying to compare for example, part1 between all six classes. I set up the functions to return the values of each of the parts but it would really suck to do if (Atlanta.getPart1() > Chicago.getPart1() && Atlanta.getPart1()> Denver.getPart1())... is there a way I can find which object has the greatest value of each attributes without having to write that out for every combination and every part?

Any help would be greatly appreciated.


Solution

  • You can use Collection.max() with proper Comparator based on abstract class

    Collections.max(
      Arrays.asList(new Atlanta(), new Pennsylvania(), ...),
      Comparator.comparing(warehouse::getPart1)
    );