0

Im trying to add an element to an array at its last position in Java, but I am not able to... Or rather, I don't know how to. This is the code at the moment:

String[] values = split(line, ",");
  int[][] coordinates = new int[2][values/2];
  for(int i = 0; i < values.length; i++) {
    if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
      coordinates[0][coordinates[0].length] = values[i];
    } else { //THIS IS ODD VALUE
      coordinates[1][coordinates[1].length] = values[i];
    }
  }

EDITED VERSION:

String[] values = split(line, ",");
  int[][] coordinates = new int[2][values/2];
  int x_pos = 0;
  int y_post = 0;
  for(int i = 0; i < values.length; i++) {
    if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
      coordinates[0][x_pos] = values[i];
      x_pos++;
    } else { //THIS IS ODD VALUE
      coordinates[1][y_pos] = values[i];
      y_pos++;
    }
  }

values is being read from a CSV file. My code is I believe wrong, since it will try to add the values always at the maximum array size for coordinates[] in both cases.

How would I go around adding them at the last set position?

Thanks!

/e: Would the EDITED VERSION be correct?

1
  • The edited version is functionally correct, and not very difficult to read. Mazbe you could make it a bit more dens this way: coordinates[0][x_pos++] = values[i];, omitting the sepatare x_pos++; line. I would hovewer use the i>>1 instead of x_pos and y_pos, because these are not needed, since the information they store are essentially stored in the i loop variable. And i>>1 is not an operation requiring much computation, I'd think it costs less than maintaining and storing x_pos and y_pos... Commented Oct 16, 2012 at 10:22

5 Answers 5

1

Your original code has two problems:

  • it addresses the array badly, the las element in a Java array is at position length-1, and this would result in an ArrayOutOfBoundsException
  • even if you'd correct it by subtracting 1, you would always overwrite the last element only, as the length of a Java array is not related to how many elements it contains, but how many elements it was initialised to contain.

Instead of:

coordinates[0][coordinates[0].length] = values[i]; 

You could use:

coordinates[0][(int)Math.round(i/2.0)] = values[i]; 

(and of course, same with coordinates[1]...)

EDIT This is ugly of course:

(int)Math.round(i/2.0)

but the solution I'd use is far less easy to understand:

i>>1

This is a right shift operator, exactly the kind of thing needed here, and is quicker than every other approach...

Conclusion: this is to be used in a live scenario:

Use

coordinates[0][i>>1] = values[i]; 

EDIT2 One learns new things every day...

This is just as good, maybe a bit slower.

coordinates[0][i/2] = values[i]; 
Sign up to request clarification or add additional context in comments.

4 Comments

I don't really understand the ">>" operator, but you helped me correct the mistakes in a different way anyway. Thanks!
>> is a bit-shift operator, taking advantage of the fact that shifting the binary representation of an integer one bit to the right is exactly equivalent to integer division by two (i.e. i>>1 == i/2).
@jslvtr the >> operator is a bitwise shift operation which is a very quick alternative to division by powers of 2. This side effect comes in handy in this exact situation. This i>>1 can be rewritten this way too: i/2 too. (Had to edit this, I was mistaken and thought 3/2 would result in 2, but simple int division doesn't do rounding)
@halex: I had to edit this, as I was wrong about the rounding issue, and i/2 is the same, and this whole trickery is not required in this case... Thanks for mentioning anyway
1

If you know you'll definitely have an even number of values you can do

for(int i = 0; i < values.length / 2; i++) {
  coordinates[0][i] = values[2*i];
  coordinates[1][i] = values[2*i + 1];
}

2 Comments

That will give IndexOutOfBounds Exception since 2*i+1 > values.length?
No, if values has (say) 6 entries then the loop will be executed 3 times, for i values 0, 1 and 2. The first time round we'll extract values[0] and [1], the second time [2] and [3], the third time [4] and [5].
0

You have to store the last position somewhere. .length gives you the size of the array.

The position in the array will always be the half of i (since you put half of the elements in one array and the other half in the other).

String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];

for(int i = 0; i < values.length; i++) {
  if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
    coordinates[0][ i / 2] = values[i];
  } else { //THIS IS ODD VALUE
    coordinates[1][ i / 2 + 1 ] = values[i];
  }
}

Comments

0

The array index for java is from "0" to "array length - 1".

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

Comments

0

why not:

String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i+=2) {
      coordinates[0][i/2] = values[i];
      coordinates[1][i/2] = values[i+1];

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.