数组和扩展的困境

Pat*_*ens 0 java arrays counter loops

所以我知道java规则是在扩展和许多其他应用程序时使用ArrayList <>.典型的阵列无法扩展.我的java课程是初级的,所以我们现在仍在审查数组.尽管我想使用一个arraylist我不能.如何将它存储到我只存储满足条件数组中条件的元素的位置?

public int[] above100Degrees()
   {
      int[] blazing = new int[temps.length];
      for( int i = 0; i < temps.length; i++ )
      {
         if( temps[i] > 100 )
         {
            blazing[i] = temps[i];
         }
      }
      return blazing;
   }
Run Code Online (Sandbox Code Playgroud)

产量

The temperature above 100 degrees is:   0   0   0   0   0   0   0   103 108 109
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

只要看看有多少元素满足您的过滤第一,然后创建数组,然后填充它.这意味着你需要经历两次数组,但除非你想最终创建多个数组,否则没有其他很好的选择.所以类似于:

public int[] above100Degrees() {
    // First work out how many items match your filter
    int count = 0;
    // Are you allowed to use the enhanced for loop? It's not necessary, but it
    // makes things simpler.
    for (int temp : temps) {
        if (temp > 100) {
            count++;
        }
    }

    // Create an array of the right size...
    int[] ret = new int[count];

    // ... and populate it.
    int index = 0;
    for (int temp : temps) {
        if (temp > 100) {
            ret[index++] = temp;
        }
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

  • @PatGreens:我建议你回过头来看看 - 但是你总是可以重写代码来使用显式索引并通过索引从数组中获取. (2认同)