正文:
直接上测试代码:
public class XMLTypeDemo {
public static void main(String[] args) {
String str = "我们的灵魂都应该是自由的,哪怕有圣洁与污秽之分。";
// true
System.out.println(str.contains("自由"));
// java.lang.NullPointerException
System.out.println(str.contains(null));
}
}
根本原因在String.contains的实现是这么回事:
/**
* Returns true if and only if this string contains the specified
* sequence of char values.
*
* @param s the sequence to search for
* @return true if this string contains <code>s</code>, false otherwise
* @throws NullPointerException if <code>s</code> is <code>null</code>
* @since 1.5
*/
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}