Denoteone
Denoteone

Reputation: 4055

Remove Null array values

I am building an array based off comparing two other arrays. But when I initalize my third array I have to set the length. But that is making my array have null objects in some instances. Is there away I can drop the empty/null postions in the array. See my code so far below:

  private String[]  tags     = new String[] { "Mike", "Bob", "Tom", "Greg" };
  private boolean[] selected = new boolean[tags.length];
  public String[] selected_tags = new String[tags.length];

        for (int i = 0; i < tags.length; i++) {
            if (selected[i] == true){
               selected_tags[i] = tags[i];
            }
        }

I left out the code for the checkboxes that builds the Boolen selected [].

Either way if I only select 2 tags then my selected_tags[] array will be Mike, Bob, Null, Null

I need to get the Null Null out. Thanks in advance!

Upvotes: 1

Views: 2640

Answers (4)

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

Instead of using a standard Java array, you should use an ArrayList : it'll allow you to add elements to it, automatically growing the list as needed.


Basically, you'd first declare / instanciate the ArrayList, without specifying any kind of size :

public ArrayList<String> selected_tags = new ArrayList<String>();

And, then, in your loop, you'd use the add() method to add items to that ArrayList :

selected_tags.add(tags[i]);

Upvotes: 2

trutheality
trutheality

Reputation: 23455

As others have mentioned, this is much easier with an ArrayList. You can even get a regular array from it with the toArray function.

Without using ArrayList, you would have to figure out the length first and not include the null values. As you can see, that's a little messy:

int length = 0;
for( boolean b : selected ) if(b) ++length; // Count the "true"s

String[] selected_tags = new String[length];
for( int i = 0, j = 0; i < tags.length; i++ )
    if( selected[i] )
        selected_tags[j++] = tags[i];

Upvotes: 2

aioobe
aioobe

Reputation: 421310

No, you can't drop the null values (and change the length of the array) after you've created it. You'll have to create a new one (or for instance use an ArrayList as illustrated below):

List<String> list = new ArrayList<String>();

for (int i = 0; i < tags.length; i++)
    if (selected[i] == true)
        list.add(tags[i]);

// Convert it to an array if needed:
selected_tags = list.toArray(new String[list.size()]);

Upvotes: 4

Petar Ivanov
Petar Ivanov

Reputation: 93090

You can use ArrayList, instead of array.

private String[]  tags     = new String[] { "Mike", "Bob", "Tom", "Greg" };
private boolean[] selected = new boolean[tags.length];
public List<String> selected_tags = new ArrayList<String>();

for (int i = 0; i < tags.length; i++) {
    if (selected[i] == true){
        selected_tags.add(tags[i]);
    } 
}

Upvotes: 9

Related Questions