Java中的String为引用类型,我们经常遇到判空的情况,str==null判断该字符串是否为null(空引用类型对象)。
str.isEmpty(),判断该字符串是否为空字符串;
str.equals(""),判断该字符串是否为空字符串。
isEmpty()和equals("")都可以判断该字符串是否为空字符串,但是equals()方法是根据str的hashcode来进行比较的,经测试,效率不如isEmpty()高。
isEmpty的实现机制就是判断str.length==0,
所以论效率而言,str.length==0高于str.isEmpty()高于equals("").
str.isEmpty(),判断该字符串是否为空字符串;
str.equals(""),判断该字符串是否为空字符串。
isEmpty()和equals("")都可以判断该字符串是否为空字符串,但是equals()方法是根据str的hashcode来进行比较的,经测试,效率不如isEmpty()高。
isEmpty的实现机制就是判断str.length==0,
所以论效率而言,str.length==0高于str.isEmpty()高于equals("").
package com.supan.test;
import junit.framework.TestCase;
public class IsStringEmpty extends TestCase {
//效率第三
public void testXiaolv1()
{
String str1 = "chenchaoyang";
Long satrt = System.currentTimeMillis();
System.out.println(satrt);
if(str1 != null && !str1.equals(""))
{
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
}
Long end = System.currentTimeMillis();
System.out.println(end);
System.out.println(satrt - end);
}
//效率第二
public void testXiaolv2()
{
String str1 = "chenchaoyang";
Long satrt = System.currentTimeMillis();
System.out.println(satrt);
if(str1 != null && !str1.isEmpty())
{
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
}
Long end = System.currentTimeMillis();
System.out.println(end);
System.out.println(satrt - end);
}
//效率最高
public void testXiaolv3()
{
String str1 = "chenchaoyang";
Long satrt = System.currentTimeMillis();
System.out.println(satrt);
if(str1 != null && str1.length() > 0)
{
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
}
Long end = System.currentTimeMillis();
System.out.println(end);
System.out.println(satrt - end);
}
}