### 初学者的问题：复制数组的某些元素

#### [英]beginner's question: copying certain elements of an array

I am trying to copy certain elements of an array into another. For example, I want to copy index 0 of lines into index 0 of links, index 3 of lines into index 1 of links, and so on (every 3 element of lines basically basically).

What I have so far keeps getting me an ArrayIndexOutOfBound error. Thank you for your help!

``````String[] lines = inputString.split(System.getProperty("line.separator"));
int j = 0;

for (int i = 0; i < lines.length; i++) {
j++;
}
``````

## 3 个解决方案

### #1

4

It sounds like you need to be incrementing `i` by 3, rather than adding 3 to `j` (but then incrementing `j` by just 1). In fact, you don't need two variables at all:

``````for (int i = 0; i < lines.length; i += 3) {
}
``````

You should also change your code to only create the array to be as large as you need:

``````String[] links = new String[lines.length / 3];
``````

Just for the sake of interest, let's have a look at what your code was actually trying to do, in terms of assignments:

``````links = lines;
// etc
``````

As you can see, this is just offsetting the index, rather than multiplying it... and as soon as `i` was `lines.length-3`, you'd end up with

``````links[lines.length - 3] = lines[lines.length]; // Bang!
``````

### #2

0

A few problems:

1. You probably want this:

``````for (int i = 0; i < lines.length; i++) {
``````

To look like this:

``````for (int i = 0; i < links.length; i++) {
``````

2. Well, yes. You are going out of bounds. Let's say `lines` is 12 elements. `links` is the same size, so you're trying to read from element 15 / 36 (depending on my correction in #1)

The solution is to make `links` smaller:

``````String[] links = new String[(int)(lines.length / 3)];
``````

Along with the correction in #1.

### #3

0

Jon Skeet has the right idea. What might be useful is to learn how to debug these things yourself. Say that `lines.length` is 5, meaning also that `links.length` is 5. What happens if you trace every iteration of the for loop?

``````i        |      j       |     j + 3
-----------------------------------------
0               0               3
1               1               4
2               2               5
``````

It'll break on this 3rd iteration. You can see that you're not accessing every three elements at all, but every element, and you're storing it in an offset position, which causes your index out of bounds exception.