Why Array.asList does not create empty list?

Marcin Pleban :

why it does not create empty list?

 String fileContent = "";
List<String> wordsList = Arrays.asList(fileContent.trim().split("[\\s]+"));

When I use:

System.out.print(wordsList.size());

It prints:

1

What is in a first position in this list? I have this problem when I want test my iterator.

My test:

@Test
    void checkIfWorksWhenNoWord() {
        String emptyString="";

        assertFalse(new WordIterator(emptyString).hasNext());
    }

My Class:

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class WordIterator implements Iterator {

    int index;
    List<String> wordsList;

    public WordIterator(String fileContent) {
        this.wordsList = Arrays.asList(fileContent.trim().split("[\\s]+"));
    }

    public List<String> getWordsList() {
        return wordsList;
    }

    @Override
    public boolean hasNext() {
        return index < wordsList.size();
    }
    @Override
    public String next() {
        if(hasNext()){

            return wordsList.get(index++);
        }
        return null;
    }
}
Andrey Tyukin :

From Javadoc 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, "".split("[\\s]+") gives Array(""), that is, an array that contains a single empty string, because the empty string is the only substring of the input string that is terminated by the end of the input string. Strange, but true.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114771&siteId=1