如何在不再次调用函数的情况下获取数组的大小?

How to get size of array without calling the function again?

我有下面的代码,两个classes,一个是main class,另一个是class1,它的功能是foo1()这个功能太多了ArrayList<> 的迭代。 foo1() 函数在主 class 中调用一次,然后调用 size 函数。

我的代码的问题是函数 getSize() 再次进行迭代以获得函数的大小。

我需要的是在不丢失有关它的信息的情况下获取已调用函数的大小。而不是再次调用该函数并获取大小,因为它很耗时。 我考虑过在 class1 中创建一个属性,然后将数组的大小分配给属性,如下所示:但我认为这不是一个好的选择,所以我正在寻找一种专业的方法。

import java.util.*;

public class HelloWorld {
  public static void main(String []args){
    class1 c = new class1();
    // foo1 function is called
    System.out.println(c.foo1());
    // get size is called, this should be in another form
    System.out.println(c.getSize());
  }     
}

public class class1{
  int size = 0;

  public ArrayList<Integer> foo1() {
    ArrayList<Integer> result = new ArrayList<>();
    for(int i = 0;i<1000;i++){
      result.add(i);
    }

    return result;
  }    

  public int getSize(){
    return foo1().size();
  }
}  

My solution which is not popular.

public class class1 {
  int size = 0;

  public ArrayList<Integer> foo1(){
    ArrayList<Integer> result = new ArrayList<>();
    for(int i = 0;i<1000;i++){
      result.add(i);
    }

    // assigning
    size = result.size();
    return result;
  }

  public int getSize() {
    return size;
  }
}

将返回值 (Arraylist) 存储在这样的变量中:Arraylist result = c.foo1() 然后在该变量上调用 size(),例如:result.size()