Is there a way to truncate arrays in Java?

Jumpem

Lifer
Sep 21, 2000
10,757
3
81
I have an array of 1500 elements, and need to pass an array of 220 to another class. Is there a way to simply truncate an array or am I going to have to create a smaller one and copy the first 220 elements over?
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
You pass a reference to the array (well, technically you pass the value of the internal pointer to the array, but more or less the same) not the array itself.

Specifically the method declaration:

public void doStuff(int[] john) {

}

does not dictate the size of the array needed to be passed. (in fact, it can't restrict the size, only the type).

What you want sounds like it should be easily accomplished using something like this:

public void doStuff(int[] john) {
int arrayLength = Math.min(220, john.length);
for (int i = 0; i < arrayLength; i++) {
//doStuff
}
}

That will allow you to access only the first 220 items (or fewer if you pass in a small array).

If you actually want to copy the values between the arrays, you will need to either use System.arraycopy or manually assign jim = john; (System.arraycopy is much more efficient).