0%

String中的三种空判断的区别

前言

我们在程序编写中常常会用到 String 是否为空的判断。
一般有三种判断字符串为空的判断方式:

1
2
3
4
5
6
7
String a;
// 三种判断空的方法
a.equals("");

if(a==null);

a.isEmpty();

然而,也是最近使用中发现这三种方法也不是任何情况下可以随便用的。
接下来,我会简单提一提。

分析

1. == 比较

==可以说我们是再熟悉不过了。但我们往往会忽略其真正的含义。

对于 Java 基本类型而言

Java 的基本类型这里简单提一下有:byte,long,int,short,float,double,char, boolean
由于这些基本类型作为变量都存储的是“值”,因此 == 对于基本类型而言就是 按值比较
例如:

1
2
3
4
5
6
int a = 2;
int b = 2;
if(a == b)
System.out.println("true");
else
System.out.println("false");

运行结果:

1
true

对于 Java 非基本类型

除了八个基本类型外,剩下的都是非基本类型(例如:String)。

非基本类型使用 == 则是 引用比较,简单的说就是比较内存地址。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
String a = new String("hello");
String b = new String("hello");
String c = "hello";
String d = "hello";

if (a == b) {
System.out.println("a==b: true");
}else {
System.out.println("a==b: false");
}

if (a == c) {
System.out.println("a==c: true");
}else {
System.out.println("a==c: false");
}

if (c == d) {
System.out.println("c==d: true");
}else {
System.out.println("c==d: false");
}

运行结果:

1
2
3
4
a==b: false
a==c: false
c==d: true

解释:

  • a==b 由于 a 与 b 都是创建的各自的对象,因此其所对应的内存地址是不同的,使用 ==的结果就是 false
  • a==c 其中 c 的内容和 a 相同,但是 a 与 c 指向的 字符串池 是不同的空间,也就是内存地址也不同,因此结果为 fasle
  • c==d c 与 d 使用同样的 ="hello"的方式创建,其实关系到 Java 的 String 的一个机制,c 创建一个字符串池内容是 "hello" ,使用赋值符号=,就是 c 指向了这个地址。对于相同的内容,Java 不会重复开创一个空间,因此 b 同样也指向同一个 引用地址 。因此使用 == 结果为 true

2. equals() 方法

我们最常用的字符串比较方法就是 String.equals() 了。
equals() 其实是定义在 Object 中的方法,因此 equals() 可以比较所有 Object 类及其子类。

看看API 中对 String 中的 equals() 的解释

1
2
3
4
5
6
7
8
9
10
11
12
equals
public boolean equals(Object anObject)

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as thisobject.
Overrides:
equals in class Object
Parameters:
anObject - The object to compare this String against
Returns:true
if the given object represents a Stringequivalent to this string, false
otherwiseSee Also:
compareTo(String), equalsIgnoreCase(String)

能看出来 equals() 的参数类型是 object ,解释中说将字符串进行比较。因此equals()比较过程中,会比较其类型是否相符,只有在相符的类型下,才会去比较其内容。

更重要一点是,参数必须是一个 String 对象且非空。如果这两点有一点不满足,则都会是false 。况且如果字符串为 null 是不能使用 equals() 或者是非法的,会出现空指针异常。

顺便一提,equals() 其内部就是利用 == 实现的。

3. isEmpty() 方法

一般也能使用 isEmpty()来判断字符串是否为空。

这里就简单说一下这个方法。
看看API的解释:

1
2
3
4
5
isEmpty
public boolean isEmpty()

Returns true if, and only if, length() is 0.
Returns:true if length() is 0, otherwise false

可以看出,isEmpty()是判断字符串的内容是否为空的。其判断依据是 length() is 0,字符串长度为0 则返回 true

总结

看来以上的详细解释,如果还不了解其直接的差距,那么只能由我简单总结一下。

就 String 字符串为空 判断而言

  • == 比较 的是 字符串变量的指向的引用/内存地址
  • equals() 比较的是同类型,且不为 null 的字符串
  • isEmpty() 判断依据是 字符串的长度是否为 0

所以根据使用情况来总结:

  • ==null 是 String 没有分配空间,仅仅只有声明而已。
    例如:String a;String a = null
  • equals("") 是 String 已分配空间,内容为空
  • isEmpty() 是 String 已分配空间,内容长度为0
  • String a = new String(); 创建的对象,是内容为 空 ,但分配了空间。

今后判断字符串是否为空,就根据具体可能的情况 使用 合理的判断方式。