Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: Can method Split return a null value?

I get a problem when reading this code.

Why does the coder determine that allProvinces = null?

if(!TextUtils.isEmpty(response)){
    String [] allProvinces = response.split(",");
    /* how should I check whether allProvinces is null or not? 
     * it means the method "split" can possibly return a null value?
     */
    if( allProvinces != null && allProvinces.length > 0){    
        for(String p :allProvinces) {
            String [] array = p.split("//|");
            Province province = new Province();
            province.setProvinceName(array [0]);
            province.setProvinceCode(array[1]);
            weatherDb.saveProvince(province);
        }
    }
}
like image 627
PodBlood Avatar asked May 31 '26 00:05

PodBlood


1 Answers

Can method Split return a null value?

split function always return String[] containing at least one element.

You get an array of size 1 holding the original value:

split method with character "-"

Input          Output
-----          ------
ABCD-XYZ      {"ABCD", "XYZ"}
QWERT         {"QWERT"}
ZXC-q-        {"ZXC","q"}
ZXC-q- -      {"ZXC","q",""}

why the coder determine allProvinces =null

It's useless to check null because split function always return String[] containing at least one element.

like image 91
N J Avatar answered Jun 01 '26 15:06

N J



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!