1

I have an empty array string

String stringArray = "[]";

And I want to convert it to an Array type.

I need this because I want to compare in an if statement if the array is empty. Like

if(stringArray.isEmpty()){
   // doSomething 
}

Any suggestion how I can do this?

3
  • 8
    How about simply stringArray.equals("[]")? How did you get such a thing in the first place? This sounds very much like an XY problem... Commented Jun 25, 2021 at 10:13
  • 1
    You could (not meaning you should) use a JSON parser to parse this array Commented Jun 25, 2021 at 10:14
  • @Sweeper I get it from another system. I extracted it then to a string. Commented Jun 25, 2021 at 11:43

2 Answers 2

2
    public static void main(String[] args) {
        String stringArray = "[]";
        Object[] array = JSON.parseArray(stringArray).toArray();
        if (array.length == 0) {
            System.out.println("array is empty");
        }
    }

output is:

array is empty
Sign up to request clarification or add additional context in comments.

2 Comments

you can use more other tools parse it as a json string to array
I wanted to try this one, which package or dependency is JSON (JSON.parseArray)?
0
String stringArray = "[]";

In this line, you didn't define an empty array. You have definee new string where the value is []

Use the code below if you would like to define an empty array

String[] stringArray ; //Define string array without initialization
String[] stringArray2 = new String[5];//Define string array with 5 element

1 Comment

Yes I know I defined a string with this "[]" value. This is what I get from another system, that's why I asked how to parse it to an array

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.