aspose file tools*
The moose likes Beginning Java and the fly likes How do I trim the null values from an array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do I trim the null values from an array?" Watch "How do I trim the null values from an array?" New topic
Author

How do I trim the null values from an array?

Zak Tacc
Greenhorn

Joined: Feb 01, 2010
Posts: 25
Hey guys need a bit of help with this.

I have an array with the following values: 1,2,3,4,5,6,null,null,null,null,null,null,null,null, etc (the number of non-null values will vary)

how do I make a method that will make the change the array to include only the non-null values? So in the above case, I'd want the array to have the following values: 1,2,3,4,5,6

I can't just set the data length to 6 because there might be more non-null values

thanks
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30537
    
150

Zak,
Are you allowed to use an ArrayList? If so, you could loop through and put all the non-null values in the ArrayList and then call a method to turn it back into an array. If not, you'd need to write two loops - do you know what they are?


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
In the java.util package there is a method called Arrays.copyOf() that may
work well. Here is how it is described in the SE-6 version of the java API.
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array.

Jim ... ...


BEE MBA PMP SCJP-6
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Jim Hoglund wrote:In the java.util package there is a method called Arrays.copyOf() that may
work well. Here is how it is described in the SE-6 version of the java API.

Unfortunately, you need to tell the size of the new array. If it's too big, it will fill the extra elements with null. If it's too short, it will truncate the original. I don't think it will remove null elements from the original.


[My Blog]
All roads lead to JavaRanch
Zak Tacc
Greenhorn

Joined: Feb 01, 2010
Posts: 25
Got it. Every time I added a value to the array, I increased the counter, and trimmed the array according to the counter. Thanks guys!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How do I trim the null values from an array?