hnvasa
hnvasa

Reputation: 860

Java - Referencing to an Array

The following is the code snippet:

int[] cdb1 = {2,1,1,5,5};
int[] cbd2 = {3,1,1,2,2,6,6};
int[] cbd3 = {3,2,2,3,3,7,7};
int[] cbd4 = {2,3,3,4,4};
int[] cbd5 = {4,4,4,5,5,6,6,7,7};
String this_cdb = "cdb"+Integer.toString(router_id);
int this_cbd_number = this_cdb[0];

I get the following error: array required, but String found int this_cbd_number = this_cdb[0];

here router_id can be 1 2 3 4 or 5. I know I declared this_cdb as String. But how do I reference it to the right array name?

Upvotes: 1

Views: 41

Answers (2)

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27476

Without reflection you can't do references to other variables/fields/classes from a String. You would need to encapsulate your arrays e.g. inside another array or a List. Example (assuming router is indexed from 1):

int[] cdb1 = {2,1,1,5,5};
int[] cbd2 = {3,1,1,2,2,6,6};
int[] cbd3 = {3,2,2,3,3,7,7};
int[] cbd4 = {2,3,3,4,4};
int[] cbd5 = {4,4,4,5,5,6,6,7,7};
int[][] cdb = {cdb1, cdb2, cdb3, cdb4, cdb5};
int this_cbd_number = cdb[router_id - 1][0];

Upvotes: 3

nhouser9
nhouser9

Reputation: 6780

Try putting all of the arrays into some kind of a data structure, like a LinkedList:

LinkedList<int[]> arrayList = new LinkedList<>();
arrayList.add(cdb1);
arrayList.add(cdb2);
arrayList.add(cdb3);
arrayList.add(cdb4);
arrayList.add(cdb5);
int this_cbd_number = arrayList.get(router_id)[0];

Upvotes: 1

Related Questions