Home > OS >  How do I check if my int array is empty, with the standard value being 0?
How do I check if my int array is empty, with the standard value being 0?

Time:12-05

So I have come across an issue I do not seem to be able to fix. So lets say I have an int array and want to check whether the array still has space to add a certain element (from 0-∞) or has no space left, which would mean I would need to create a new array.

The issue is that when my int array has a space to store ten values, all of the spaces are filled with 0, so my program thinks that this array is full. And I can not exclude 0 either because the element which I want to add could be 0 aswell.

Any advice?

CodePudding user response:

You are probably using an int[]? The primitive type int can not be null. A very simple solution would be to use the wrapper class Integer.

Integer[] intArray = {null, 0, 10};

CodePudding user response:

You need to keep track of which positions are filled via additional variables. A Java array itself (when created) is initialized with 0-s and it is technically always full.

If you need a dynamically expanding array, my suggestion is to use java.util.List, which is very handy and in most situations can replace a Java array nicely.

A List tutorial is easy to find, here is an example .

And this is how you use it:

import java.util.ArrayList;
import java.util.List;

....
List<String> a = new ArrayList<>();
a.add("Hello");
a.add("World");
System.out.println(a.size());

You can easily convert to a standard array: a.toArray().

CodePudding user response:

If your numbers are always greater or equal 0, you could just set unused numbers to -1.

  • Related