smasherCoder
smasherCoder

Reputation: 41

Trying to write a method to find the largest object from an array

Add a method:

public static Measurable max(Measurable[] objects)

to the Data class that returns the object with the largest measure.

This is what I have for code:

public interface Measurable
{
    double getMeasure();
}

And the part I am having problems with:

public class Data {
  //I am trying to come up with a method here

  public static Measurable max(Measurable[] objects){
    double max = 0;
    for (Measurable obj : objects){
      if (obj.getMeasure() > max){
          obj =  max;
      }  
    }
   return max;
  }
}

Upvotes: 3

Views: 808

Answers (3)

SELA
SELA

Reputation: 6803

You were almost there. Initially set the max value to object[0] by max =objects[0] and then compare it with each iteration.

Refer the below code:

public class Data {
  public static Measurable max(Measurable[] objects){
    Measurable max = objects[0];  
    for (int i = 1; i < objects.length; i++) {
        if (objects[i] > max) {
            max = objects[i];
        }
    }
   return max;
  }
}

Upvotes: 0

M. Justin
M. Justin

Reputation: 21094

One fairly idiomatic approach using the built-in Java libraries would be to use Stream.max:

import java.util.Arrays;
import java.util.Comparator;

public class Data {
    private static final Comparator<Measurable> MEASURABLE_COMPARATOR =
            Comparator.comparing(Measurable::getMeasure);

    public static Measurable max(Measurable[] objects){
        return Arrays.stream(objects).max(MEASURABLE_COMPARATOR).orElseThrow();
    }
}

Upvotes: 0

adarsh
adarsh

Reputation: 1503

The max method should be like:


public static Measurable max(Measurable[] objects) {
   Measurable max = null;
   for (Measurable obj : objects) {
       if (max == null || obj.getMeasure() > max.getMeasure()) {
              max = obj;
       }  
    }
       return max;
}

If you're using Java 8, you could do:

public static Measurable max(Measurable[] objects) {
  return Arrays.stream(objects).max(Comparator.comparing(Measurable::getMeasure)).get();
}

Also, using

for (Measurable obj : objects){

without null check is a recipe for NullPointerException.

---- Edit ------
Using the max method:

Measurable max = Data.max(countries) // gives max measure containing object
System.out.println(max.getMeasure()) // prints the max measure value

Upvotes: 2

Related Questions