Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate an array without copying it?

Tags:

java

In Java, is there a way to truncate an array without having to make a copy of it? The common idiom is Arrays.copyOf(foo, n) (where the new array is n elements long). I don't think there is an alternative, but I'm curious as to whether there is a better approach.

like image 408
Rob Avatar asked Sep 05 '25 04:09

Rob


1 Answers

An array's length in Java cannot be altered after initialization, so you're forced to make a copy with the new size. Actually, the length parameter of a Java array is declared as final, so it cannot be changed once it's set.

If you need to change an array's size, I'd use an ArrayList.

like image 175
AlbertoPL Avatar answered Sep 07 '25 17:09

AlbertoPL