Java数组,使用数组元素作为引用从另一个数组中获取元素,然后创建另一个新数组

时间:2017-08-10 11:33:03

标签: java arrays

有没有人知道如何使用数组作为引用,通过使用for循环或其他有用的方法获取另一个数组中的元素? 例如,我在下面有多个数组,在运行程序之后,输出数组将具有

int[] array = { 0, 1, 3, 4, 5, 6, 8 };
int[] c = { 18, 19, 20, 21, 22, 23, 24, 25, 26 };

我运行程序后

output ={18,19,21,22,23,24,26}


//this is generate through below
output[0]=c[0];
output[1]=c[1];
output[2]=c[3];
output[3]=c[4];

3 个答案:

答案 0 :(得分:1)

由于数组索引是通常的整数值,因此它们不需要硬编码:

int[] indeces = { 0, 1, 3, 4, 5, 6, 8 };
int[] values = { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
int[] output = new int[indeces.length]

for (int i = 0; i<indeces.length; i++) {
    output[i] = values[indeces[i]];
}

(未经测试的代码)

答案 1 :(得分:0)

您可以访问以下值:

output[i]=c[array[i]];

我要把它留给你来围绕声明组装循环:)

答案 2 :(得分:0)

您可以使用以下代码来实现此目的

int[] array = { 0, 1, 3, 4, 5, 6, 8 };
 int[] c = { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
 int output [] = new  int[array.length];
 int cnt =0 ;
 for(int a : array){
     if(a < c.length && a >= 0){
      output[cnt++]=c[a];
      }
 }

这是一个非常简单的解决方案,当然还有其他方法可以实现相同的