Home > OS >  Creating new object sets all existing ones to null (Java)
Creating new object sets all existing ones to null (Java)

Time:03-18

I have this method which is supposed to cut a String when it finds a symbos of or - (it is part of a derivative calculator, so the idea is to get a bunch of small strings separated by or - and then derivate them one by one. That's why i have that search for opened and closed parenthesis) The problem is: When calling res = new String(); it will create a new String, but it will also set all the existing String objects in the array to null, which means the return of the method will always be an array with everything set to null (unless it does not find a or - in the function). Is there a way around this?

public static String[] cutString(String func)
        {
            
            int number_strings_res = 0;
            int number_parenthesis = 0;
            String[] res = new String[1];
            res[0] = new String(func);
            for(int i = 0; i < func.length(); i  )
            {
                if(func.charAt(i) == ' ' || func.charAt(i) == '-')
                {
                    for(int j = 0; j < i; j  )
                    {
                        if(func.charAt(j) == '(')
                            number_parenthesis  ;
                        if(func.charAt(j) == ')')
                            number_parenthesis--;
                    }
                    if(number_parenthesis == 0)
                    {
                        res[number_strings_res] = "";
                        for(int j = 0; j < i; j  )
                        {
                            res[number_strings_res]  = func.charAt(j);
                        }
                        number_strings_res  ;
                        res = new String[number_strings_res   1];
                        res[number_strings_res] = new String(Character.toString(func.charAt(i)));
                        number_strings_res  ;
                        res = new String[number_strings_res   1];
                        res[number_strings_res] = new String();
                    }
                }
            }
            return res;
        }

CodePudding user response:

res = new String[number_strings_res 1] allocates a new array and stores it to res. So that's the source of the immediate problem. You should probably be using a List, like ArrayList, instead if you don't know how long the collection will be.

CodePudding user response:

When calling res = new String() ...

You have no such call, and it would not compile anyway.

'res' is declared as variable referring to a String array. When you execute res = new String[...] you naturally replace the entire array of Strings.

But I can't really figure out what you intend? Are you trying to extend the array? You can't, directly.

If you must use an array, look into Arrays.copyFrom. But an ArrayList would be easier.

  • Related