Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Array.asList does not create empty list?

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;
    }
}
like image 736
Marcin Pleban Avatar asked Sep 08 '26 10:09

Marcin Pleban


1 Answers

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.

like image 91
Andrey Tyukin Avatar answered Sep 10 '26 23:09

Andrey Tyukin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!