问题:比较两个字符串是否相等?
解决办法:使用==
方法,使用该方法的好处是即使当字符串为null
时,他也不会抛出NullPointerException
。
1 | val s1 = "hello" |
如果不考虑字符的大小写,需要先将比较的字符串转化为全部大写。1
2
3
4val s1 = "hello"
val s2 = "Hello"
println(s1.toUpperCase == s2.toUpperCase)
但是这样如果比较的双方有一个为null
,则会抛出NullPointerException
。
原因分析
为什么==
不会抛出NullPointerException
?
这是应为==
其实是一个函数,来自于scala.AnyRef
.
看一下官方文档:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38class AnyRef extends Any
class AnyRef is the root class of all reference types.All types except the value types descend from this class.
Linear supertypes
Any
value Members
final def !=(arg0: Any):Boolen
Test two objects for inequality
final def ##(): Int
Equivalent to x.hashCOde except for boxed numeric types and null
final def ==(arg0: Any):Boolean
The expression x == that is equivalent to if(x eq null) that eq null else x.equals(that).
final def eq(arg0: AnyRef): Boolean
Tests whether the argument(that)is a refrence to the receiver object(this)
def equals(arg0: Any): Boolean
The equality method for reference types
final def getClass(): Class[_]
Returns the runtime class representation of the object
def hashCode(): Int
The hashCode method for the reference types
final def ne(arg0: AnyRef): Boolean
Equivalent to !(this eq that)
final def notify(): Unit
Wakes up a single thread that is waiting on the receiver object's monitor.
final def notifyAll(): Unit
Wakes up all threads that are waiting for on the receiver object's monitor
final def synchronized[T0](arg0: => T0): T0): T0
def toString(): String
createa a String representation of this object
final def wait(): Unit
final def wait(arg0: Long, arg1:Int): Unit
final def wait(arg0: Long): Unit