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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With