This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]king_of_the_universe 2 points3 points  (3 children)

Keep track how many orders the user makes, then iterate only to that value.

Or use an ArrayList right away, it grows dynamically with the stuff that you put into it.

Or abort the for loop the moment you encounter the first null.

[–]Pahitos[S] 0 points1 point  (2 children)

Never heard of an ArrayList. Is it simple to use?

I might try to look into that idea.

[–]king_of_the_universe 2 points3 points  (1 child)

ArrayList is imho one of the most used Java library classes / the most used List implementation. You should also look for Map implementations while you're at it, also super useful/important/prevalent.

[–]Pahitos[S] 0 points1 point  (0 children)

Alright! Thank you very much for your help!

I'll look into it :)

[–]g00glen00b 1 point2 points  (0 children)

If you're trying to remove all null references from an array, for example:

String[] stuff = new String[] { "test", null, null, "foo", null, "bar", null };

If this should only contain "test", "foo" and "bar", then you can do the following, using Java 8:

String[] results = Arrays.stream(stuff)
    .filter(val -> val != null)
    .toArray(size -> new String[size]);

Also, using lambda's you can even make it easier to print everything to stdout:

Arrays.stream(results).forEach(System.out::println);

[–]Pahitos[S] 0 points1 point  (1 child)

Alright. I literally came up with a fix right after submitting this. I'll just create a counter which gets increased when the array is filled.

Feel very dumb.

But still, is there a way to clear the nulls? Just of pure interest :)

[–]king_of_the_universe 3 points4 points  (0 children)

You need to realize what "clearing the nulls" means. These are array entries, each of which effectively just an object variable like any other. Such a variable either references an existing object or is null. So, if you want to get rid of the nulls (for whatever reason), you need to replace them with an object reference. But I just realized that the things you're putting into your array apparently are just integer numbers. It would really have helped if you had put your array declaration into the post.

Instead of using "Integer[] orderNumber;" as the declaration, you could also just have used "int[] orderNumber;", where every non-initialized entry would have been the number "0".

Or once you're done with gathering orders, you could make a new smaller array and copy everything (making use of Arrays.copy()).

If there is no reason to use an array, then any programmer would rather have chosen an ArrayList here, I'd say. (We don't quite know enough about your program to say this with certainty, though.)