Java – Android ArrayList size returns 1 even if there are no items in the list

Android ArrayList size returns 1 even if there are no items in the list… here is a solution to the problem.

Android ArrayList size returns 1 even if there are no items in the list

I’m using Android. I have an ArrayList of string data, and I save the entire Arraylist as a single string in a local database. Later I get this string from the database and convert this string to an array list

Case 1:

  String dbString=[10,5,34,67];   array list as string
  String replace = dbString.toString().replace("[", "");
            String replace1 = replace.replace("]", "");
            mysignimgList = new ArrayList<String>(Arrays.asList(replace1.split(",")));

Case 2:

  String dbString2=[];  empty array list as string
  String replace = dbString2.toString().replace("[", "");
            String replace1 = replace.replace("]", "");
            mysignimgList2 = new ArrayList<String>(Arrays.asList(replace1.split(",")));

But in the second case, even if there are no items in the arraylist, its size will become mysignimgList2.size()=1.

Solution

This is A feature of String.split

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.

Therefore, splitting an empty string returns an array of 1 items containing an empty string.

Related Problems and Solutions