• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do I trim the null values from an array?

 
Zak Tacc
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author & internet detective
Marshal
Posts: 34860
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ... ...
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Zak Tacc
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic