0

I have string array str[10][3], it is full of values. Now I want to make it empty ie. delete all the values of str. I have defined str as static, also I want empty this string from another claas in same package. Can I use null here.

Plz suggest some way. thanks

3
  • 2
    Have you tried either removing the reference to the array (str = null), or going through each element and setting it to null? Commented Mar 15, 2012 at 4:48
  • Why is it you want to delete all of the strings? Will you be using them again? There might be a better solution to your problem rather than setting them all to "" or null (which, you can do). Commented Mar 15, 2012 at 4:50
  • @Makoto and Deco I have check string for empty before reusing them, so it is compulsary to make them empty. Commented Mar 15, 2012 at 5:02

3 Answers 3

3

Sure, you can use null but first wonder if you really need to nullify them, because null values will mostly generate problems and require special handling. You could use the empty string "" to avoid having problems with NullPointerExceptions.

Just reassign a new array to the same variable will do the trick, Java will take care about collecting garbaged data:

ClassName.str = new String[10][3];
Sign up to request clarification or add additional context in comments.

1 Comment

@adrian I dont want strings marked for garbage collection, I just want to resue them and before reusing them I must comfirm that string is empty..
0

str = new String[10][3]; will assign an empty 2D array to str.

Comments

0

One can always sets a value to null as long as it is no primitive type (int, char, boolean, ...) or a readonly value. I assume it's neither of them so the answer is YES.

So a solution would be:

str = null;

If you want to fill up your structure with new values you could use

str = new String[10][3];

however I don't see why you should do that, It's not because you don't need the data you should get rid of it. Furthermore in the new str there is also data (the initial null-strings). But if you wan't to store new data into the structure, there is no problem to do so. This paradigm is sometimes called "lazy". It means: "don't do anything unless you absolutly have to"

By setting null the data will not disappear at once. It is sheduled to be removed by the garbage collector. A program that only runs at some low frequency or if the program is in need of memory. In that case it wil mark the memory as free so it can be reused.

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.