Java Contains()方法傳入空(非null)字符串的返回結果


Contains為字符串操作中常用的方法,用來判斷字符串以及子串是否包含目標串。然而String和String集合調用Contains方法傳入空串(“”)的返回結果是不一致的。
1、Str.contains(“”)返回true
當Str為字符串時,Str.contains()方法的JDK源碼為

public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }

調用的是indexOf方法,那么Str.indexOf(“”)的返回結果是怎樣呢?
Str.indexOf(“”)返回的是0,而非-1,因此Str.contains(“”)返回true。

2、Strs.contains(“”)若子串中有“”字符串則返回true,否則返回false
當Strs為字符串集合時(Set,List等),Strs.contains()方法的JDK源碼為:

public boolean contains(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
        return false;
    }

 

此時,若Strs集合中沒有為“”的子串那么,Strs.contains(“”)返回false,有則返回true。

另外,通過集合類字符串的源碼我們可以看出,Strs.contains(null)是合法的,並且當字符串集合中允許有null並且有null子串時,Strs.contains(null)返回true。而Str.contains(null)會報NPE(空指針異常)!

 

"".indexOf()的作用,以及結果標識 1、0、-1

"".indexOf()的作用,以及結果標識 1(不限於1,而是發現的字符的起始位,從0開始)、0、-1

String str1=“{I am ok:1234}”.indexOf("123");


str1=9;



·String str1=“1234}”.indexOf("123");


str1=0;


·String str2=“{I am ok:1234}”.indexOf("");


str1=0;



·String str3=“{I am ok:1234}”.indexOf("12345");


str1=-1;


上面的3個結果說明,對字符串使用indexOf()方法可以有3種使用效果


第一種是被比較的字符串具有比較的字符串,所得結果返回為 1或者0,這是返回的存在這個字符串的起始位置第0位開始,或者第1位開始出現這個字符串


第二種是和空字符串比較,返回的是0,如果使用空字符串和空字符串做比較,返回的還是0


第三種是和一個不存在的字符串做比較,返回的是-1


如果說,我們已經可以預知兩種結果中的特殊標志位,就是返回的string中要么有 "right",要么就是"false",這樣的字段,那可顯然,可以直接讓string的串和right來一個indexOf("right"),如果返回為0或者大於0的整數,說明返回的是正確的結果,否則,也就是等於  -1 時,就是錯誤的string串了,當然,使用表示"false"字段的比較也是可以的。

 

轉自:https://blog.csdn.net/q563730343/article/details/82149601


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM