I am afraid you'll have to do a linear search:
public static WaterBody mostPowerful(WaterBody[] waterBodies) {
double maxValue = -1;
int indexOfMaxValue = -1;
for(int i = 0; i < waterBodies.length; i++) {
if(waterBodies[i].getElectricPower() > maxValue) {
indexOfMaxValue = i;
}
}
return waterBodies[indexOfMaxValue];
}
A more elegant solution can be achieved by using a Comparator. It defines an Interface, which tells if one object is "bigger" or "smaller" than another. You can define a Comparator like that:
Comparator<String> cmp = new Comparator<WaterBody>() {
@Override
public int compare(WaterBody o1, WaterBody o2) {
return Double.compare(o1.getElectricPower(), o2.getElectricPower());
}
};
If you'll need do operations like these often, it is advised to have a collection which always keeps it's content sorted, like a TreeSet
It would be a lot smarter to use a collection, which keeps it's content sorted.
TreeSet<WaterBody> waterBodiesTree = new TreeSet<>(cmp);
Collections.addAll(waterBodiesTree, waterBodies);
WaterBody smallest = waterBodiesTree.first();
WaterBody biggest = waterBodiesTree.last();
If you only need to sort your array, the first example I used turns into a one-liner (using the same Comparator as defined earlier):
public static WaterBody mostPowerful(WaterBody[] waterBodies) {
return Collections.max(waterbodies, cmp);
}
maxvalto store the object with the maximum value, iterate over the array with foreach, callgetElectricPower()on each object and compare its value with the value from the object in your variable. If it is greater it is your new maximum object (assign it tomaxval). Try to code it yourself, it can be fun! Show your code if it doesn't work out immediately