1

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?

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

}

Comments

0

Have you tried:

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

2 Comments

Yes, but the method can only take in the index as a parameter
Have a private static array as one of the class variables?
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.