0

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?

2
  • 3
    Have a counter. Special values are a bad idea. Commented Dec 4, 2021 at 12:34
  • An IntBuffer is almost certainly what you want. For example, IntBuffer values = IntBuffer.allocate(10); Commented Dec 4, 2021 at 13:36

3 Answers 3

2

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};
Sign up to request clarification or add additional context in comments.

4 Comments

Interesting solution! Nice.
At the expense of memory.
But maybe ,as mentioned in another answer, a List is a better solution for you.
Thanks! Thats the simple solution I was looking for!
1

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().

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.