一、判断字符串为空的方法
1、字符串为空情况
字符串指向null
字符串指向一个对象,对象为""
2、字符串为空判断
if(data == null || "".equals(data))
if(data == null || data.length <= 0)
if(data == null || data.isEmpty())
if(data == null || data == "")
注意:此时的方法四只针对字符串常量生效,赋予初始值
== 比较的是两个对象内存中的地址,例如:
String data1 = new String(“A”);
String data2 = new String(“A”);
data1与data2就是两个对象,他俩使用==比较的结果是false
3、编写程序测试其效率
package java_basics;
/**
* @ClassName StringTest
* @Author wwl
* @Date 2020/8/26 18:27
* @Version 1.0
**/
public class StringTest {
public static void main(String[] args) {
String name = "jfefa;ekfklfwjflkjaflajogwogjoasgoa";
long l1 = System.currentTimeMillis();
for(int i = 0 ; i < 10000 ; i++){
for(int j = 0 ; j < 10000 ; j++){
if(name == null || "".equals(name));
}
}
long l12 = System.currentTimeMillis();
System.out.printf("方法1判断为空,10000*10000次消耗时间:%s ms\n",String.valueOf(l12 - l1));
long l2 = System.currentTimeMillis();
for(int i = 0 ; i < 10000 ; i++){
for(int j = 0 ; j < 10000 ; j++){
if(name == null || name.length() <= 0);
}
}
long l22 = System.currentTimeMillis();
System.out.printf("方法2判断为空,10000*10000次消耗时间:%s ms\n",String.valueOf(l22 - l2));
long l3 = System.currentTimeMillis();
for(int i = 0 ; i < 10000 ; i++){
for(int j = 0 ; j < 10000 ; j++){
if(name == null || name.isEmpty());
}
}
long l32 = System.currentTimeMillis();
System.out.printf("方法3判断为空,10000*10000次消耗时间:%s ms\n",String.valueOf(l32 - l3));
long l4 = System.currentTimeMillis();
for(int i = 0 ; i < 10000 ; i++){
for(int j = 0 ; j < 10000 ; j++){
if(name == null || name == "");
}
}
long l42 = System.currentTimeMillis();
System.out.printf("方法4判断为空,10000*10000次消耗时间:%s ms",String.valueOf(l42 - l4));
}
}
运行结果: