【问题标题】:Using a for-each loop to return largest value in arraylist使用 for-each 循环返回数组列表中的最大值
【发布时间】:2018-03-29 21:17:21
【问题描述】:

我在编写一个 for-each 循环时遇到了麻烦,该循环搜索 arraylist 并返回大陆内具有最高 gdp 的县名。这是我现在的代码。 (ElementsList就是原来的ArrayList)

public Country highestGdp(String continent) {
    boolean flag;
    for (Country cont : ElementsList) {
        if (cont.getContinent().equals(continent)) {
            ArrayList<Country> TMP1 = new ArrayList<Country>();
            TMP1.add(cont);
            for (Country gdp : TMP1) {
                double max = 0;

                if (max < gdp.getGDP()) {
                    max = gdp.getGDP();

                }
                if (gdp.getGDP() == max) {
                    ArrayList<Country> TMP2 = new ArrayList<Country>();
                    TMP2.add(gdp);
                }
                return gdp;
            }
        }
    }
    return null;
}

【问题讨论】:

  • 您应该尝试在两个单独的循环中执行此操作,或者在每次找到新国家/地区时检查最大值。不需要有两个嵌套循环。

标签: java arraylist foreach


【解决方案1】:

每次您在正确的大陆上找到一个国家时,您都可以检查它是否大于迄今为止的最大值。不需要每次都遍历所有这些。

public Country highestGdp(String continent) {
    boolean flag;
    Country maxCountry = null;
    for (Country cont : ElementsList) {
        if (cont.getContinent().equals(continent)) {
            if (maxCountry == null) maxCountry = cont;
            if (maxCountry.getGDP() < gdp.getGDP()) {
                maxCountry = cont;
            }
        }
    }
    return maxCountry;
}

【讨论】:

    【解决方案2】:

    抱歉,您的代码有点乱;)

    为了尽快解决您的问题,请尝试在循环之前移动 max 声明,如下所示:

    [...]
    double max = 0; 
    for(Country gdp : TMP1){
    [...]
    

    我们可以看到TMP2完全没用,去掉它:

     // ArrayList<Country> TMP2 = new ArrayList<Country>();    
     // TMP2.add(gdp);
    

    您始终只使用 1 个元素创建 TMP1 列表,然后对其进行迭代。这也没用,你可以直接在你要添加到列表的元素上做代码。

    ElementList 的第一次迭代是 Country 元素的列表,但您迭代的元素称为 cont (=continent),它是 Cont,而不是 Country。是否打算使用 Country 类来涵盖:国家和大陆?您是否打算有一个像“大陆包含许多国家”这样的树状结构?

    解决原始问题的最终代码应该是这样的:

     public Country highestGdp(String continent){
        Country countryWithMaxGdp = null;
            for(Country cont: ElementsList ){
            if(cont.getContinent().equals(continent)){
               if(countryWithMaxGdp == null || countryWithMaxGdp.getGDP() < cont.getGDP()){
                 countryWithMaxGdp = cont;
                }    
            }
        }
        return countryWithMaxGdp;
     }
    

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 2019-09-18
      相关资源
      最近更新 更多