尝试编写一个方法来从数组中查找最大的对象

问题描述 投票:0回答:1

添加方法:

public static Measurable max(Measurable[] objects)

到返回具有最大度量的对象的

Data
类。

这就是我的代码:

public interface Measurable
{
    double getMeasure();
}

public class MeasurableTester {

    public static void main(String[] args) {
        Measurable[] accounts = new Measurable[3];
        accounts[0] = new BankAccount(0);
        accounts[1] = new BankAccount(10000);
        accounts[2] = new BankAccount(2000);
        
        double averageBalance = Data.average(accounts);
        System.out.println("Average balance: " + averageBalance);
        System.out.println("Expected: 4000");
        
        Measurable[] countries = new Measurable[3];
        countries[0] = new Country("Uruguay", 176220);
        countries[1] = new Country("Thailand", 513120);
        countries[2] = new Country("Belgium", 30510);
        
        double averageArea = Data.average(countries);
        System.out.println("Average area: " + averageArea);
        System.out.println("Expected: 239950");
    }

}

我遇到问题的部分:

public class Data {
  Object tempObj = new Object();

  public static double average(Measurable[] objects){
      double sum = 0;
      for (Measurable obj : objects){
          sum = sum + obj.getMeasure();
      }
      if (objects.length > 0) {
          return sum / objects.length;
      }else{
          return 0;
      }
  }

  //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;
  }
}
java arrays max
1个回答
2
投票

max
方法应该是这样的:


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

如果您使用 Java 8,您可以这样做:

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

另外,使用

for (Measurable obj : objects){

没有

null
检查是
NullPointerException
的秘诀。

---- 编辑------
使用

max
方法:

Measurable max = Data.max(countries) // gives max measure containing object
System.out.println(max.getMeasure()) // prints the max measure value
© www.soinside.com 2019 - 2024. All rights reserved.