Labra
Labra

Reputation: 51

Using an array in a method that has been created in another method

How do I write a method, that has a parameter integer representing the index, and returns the value the array holds at the specified index. But the array being used has been generated by a previous method. So far I have this:

public static int get(int var)  {

 int[] result = constructArray(arrayA,array B);
    return result[var];
}

The main method looks like

  public static void main(final String[] args) {

        int[]result = constructArray(arrayA,arrayB);
        System.out.println(Arrays.toString(result));
        int variable = get(2);
        System.out.println(variable);


}

The method constructArray constructs a different array each time it is called, so when I call the get method I want to use the array that has already been constructed. How can I achieve this?

Upvotes: 1

Views: 84

Answers (5)

D-zer0
D-zer0

Reputation: 63

If these methods reside in the same class it should be a fairly simple matter to initialize and reference the generated array directly

public static int get(int var)  {

    return result[var];
}

Upvotes: 0

bancer
bancer

Reputation: 7525

This should be okay in your case:

public static void main(final String[] args) {
    int[]result = constructArray(arrayA,arrayB);
    System.out.println(Arrays.toString(result));
    int variable = result[2];
    System.out.println(variable);
}

Upvotes: 0

aldrin
aldrin

Reputation: 4572

Save the array as a static member of the class after you construct it the first time

class Example {

  static int[] result; 

  public static void main(final String[] args) {
      result = constructArray(arrayA,arrayB);
      System.out.println(Arrays.toString(result));
      int variable = get(2);
      System.out.println(variable);
  }

  public static int get(int var)  {
      return result[var];
  }

}

Upvotes: 1

Alex
Alex

Reputation: 1345

Have you tried:

public static int get(int[] array ,int index)  {
    return array[index];
}

Upvotes: 0

jzd
jzd

Reputation: 23629

Save the array into a temporary variable somewhere higher in scope and only rebuild the first time. Ideally you would just build it when you construct the object that uses it.

Depending your design you could also build the array at a higher level and pass it as a second parameter to the get() method.

Upvotes: 2

Related Questions