I need to create a method compact that can remove all zeroes from an array and leave the order of other elements unchanged, but without creating a new array. The method must actually remove all zeroes, not just print out the other elements, and it should only use one private array. So 0, 9, 7, 0, 0, 23, 4, 0 would turn into 9, 7, 23, 4. I've been stuck since everything I have have found online says it is impossible to remove elements from an array without creating a new array, so any help would be much appreciated.
Jump to Post
Without creating new array the best you can do is to compress out the zeros, then fill the unused elements at the end of the array with zeros. Ie 9 7 23 4 0 0 0 0
There is no way to change the size of a Java array after …
Jump to Post
By default, when you declare and create a new array, each element is set to 0.
So, using this logic we can conclude that if you remove a 0 from the array, Java replaces it with the default value, 0.
There are two simple options.
1. Bite the bullet use …
All 7 RepliesReply to this topic
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.