2016-04-09 68 views
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}; 
String this_cdb = "cdb"+Integer.toString(router_id); 
int this_cbd_number = this_cdb[0]; 

我收到以下错误:数组必需的,但字符串发现 int this_cbd_number = this_cdb[0];

这里router_id可以12345。我知道我宣称this_cdbString。但是,我如何将它引用到正确的数组名称?

回答

3

没有反射,你不能从一个字符串做其他变量/场/类的引用。 你需要封装你的阵列,例如在另一个阵列内或List。示例(假设路由器索引从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]; 
+0

它应该是[router_id-1]对不对? – hnvasa

+0

是的,你是对的,更正 –

1

尝试把所有的阵列变成某种数据结构,就像一个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];