-2

Consider we are evaluating some value and based on that we are assigning the name of the array i.e

if (Value == 1) {
        set array_name "One"
    } else {
        set array_name "Some_Number"
    }
    type[] array_name;//Set the Array name here
}

Can we create dynamic names of array in java ?

Gani
  • 422
  • 1
  • 8
  • 16

3 Answers3

1

Possible alternative can be;

//populate array with whatever name
int[] arrayA = new  int[3];
    for(int i=0;i<arrayA.length;i++) {
        arrayA[i]=i*10;
    }
//copy the previously populated array to the desired name array
if (Value == 1) {
    int[] one = arrayA;
} else {
    int[] some_number = arrayA
}
Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25
1

As you haven't mentioned the use case, but if you want to assign array a name based on a condition and later want to access the array with the same name, you can use a HashMap.

HashMap<String,String[]> arrayMap = new HashMap<>();
if (Value == 1) {
    arrayMap.put("One",youArray);
} else {
        arrayMap.put("some_number",youArray);
}
String[] myArray = arrayMap.get("One");

Hope this helps.

Jatin Asija
  • 128
  • 4
  • 13
0

This is not possible in Java. Variable names cannot be set or changed dynamically.

Henry
  • 42,982
  • 7
  • 68
  • 84