Search code examples
javaarraystime-complexityspace-complexity

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


I have the code below, two classes, one is the main class and the other is class1 which has the function foo1() this function make too many iterations over an ArrayList<> . the foo1() function is called once in the main class, and then the size function is called.

The problem with my code is that the function getSize() is making iteration again to get the size of the function.

What i need is to get the size of the already called function without losing the information about it. and not to call the function again and getting the size because its time consuming. I thought about making an attribute in the class1 and then assign the size of the array into the attribute like the following: but its not a good choice i think, so i am looking for a professional approach.

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;
  }
}

Solution

  • Store returned value (Arraylist) in a variable like this : Arraylist result = c.foo1() and then call size() on this variable like: result.size()