Most efficient way to find object with highest value

时间:2018-07-25 04:26:44

标签: java arrays

I have a dynamically created array of Box objects where the user inputs an amount of boxes then enters their dimensions

Each Box object has multiple variables, but I'm interested in finding the box with the highest totalArea variable as i'm trying to figure out which size fills up a space the most efficiently

I can do this very simply with:

int amount = 0, boxNum;

for (int i=0; i<boxes.length;i++)
    if (boxes[i].totalArea > amount){
        amount = boxes[i].totalArea;
        boxNum = i+1;
    }

but I feel as if i'm doing more work than necessary by declaring three variables. I'm wondering if there is a more efficient way to achieve this. My first thought was using an enhanced for loop, but that's a no go, as finding the current index of the iteration isn't a viable route. Now it's probably not a big deal, but for the sake of optimization and learning, is there a better, faster way to do this?

edit: This example is not a duplicate of this question as Collections.max() is used for collections like arrayLists, not generic arrays

0 个答案:

没有答案