Java – Copy String array and remove empty strings

arraysjavastring

I want to eliminate empty elements within my String array. This is what I have tried so far:

String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(str[i] == "")
    {

    }
    else
    {
        xml[i] = str[i]; 
    }
}
String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(!str[i].equals(""))
    {
        xml[i] = str[i]; 
    }
}
String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(!str[i].isEmpty())
    {
        xml[i] = str[i]; 
    }
}
String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(str[i].isEmpty() == false)
    {
        xml[i] = str[i]; 
    }
}

No matter which one I try, it always copies all the values. I've checked the locals, and it is clear that there are empty arrays within the String array.

Best Solution

Try this,

b = Arrays.copyOf(a, a.length);

Or

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

Or

b = a.clone();