您的位置:首页 > 编程语言 > Java开发

Java判断字符串是否为空的方法

2013-01-28 15:37 399 查看
以下是
Java 判断字符串是否为空的几种方法.
  方法一: 最多人使用的一个方法, 直观, 方便, 但效率很低.

  方法二: 比较字符串长度, 效率高, 是我知道的最好一个方法.

  方法三:
Java SE 6.0 才开始提供的办法, 效率和方法二基本上相等, 但出于兼容性考虑, 推荐使用方法二或方法四.

  方法四: 这是种最直观,简便的方法,而且效率也非常的高,与方法二、三的效率差不多

  以下代码在我机器上的运行结果: (机器性能不一, 仅供参考)

  function 1 use time: 140ms

  function 2 use time: 47ms

  function 3 use time: 47ms

  function 4 use time: 47ms

既然文章作者说机器性能不一,我就在自己电脑上测试了一下,三次运行结果分别如下:

function 1 used time: 93ms

function 2 used time: 40ms

function 3 used time: 44ms

function 4 used time: 35ms

------------------------------------

function 1 used time: 75ms

function 2 used time: 39ms

function 3 used time: 43ms

function 4 used time: 35ms

------------------------------------

function 1 used time: 74ms

function 2 used time: 40ms

function 3 used time: 44ms

function 4 used time: 36ms

  Java代码

  public class TestEmptyString {

  String s = "";

  long n = 10000000;

  private void function1() {

  long startTime = System.currentTimeMillis();

  for (long i = 0; i < n; i++) {

  if (s == null || s.equals(""))

  ;

  }

  long endTime = System.currentTimeMillis();

  System.out.println("function 1 use time: " + (endTime - startTime)

  + "ms");

  }

  private void function2() {

  long startTime = System.currentTimeMillis();

  for (long i = 0; i < n; i++) {

  if (s == null || s.length() <= 0)

  ;

  }

  long endTime = System.currentTimeMillis();

  System.out.println("function 2 use time: " + (endTime - startTime)

  + "ms");

  }

  private void function3() {

  long startTime = System.currentTimeMillis();

  for (long i = 0; i < n; i++) {

  if (s == null || s.isEmpty())

  ;

  }

  long endTime = System.currentTimeMillis();

  System.out.println("function 3 use time: " + (endTime - startTime)

  + "ms");

  }

  private void function4() {

  long startTime = System.currentTimeMillis();

  for (long i = 0; i < n; i++) {

  if (s == null || s == "")

  ;

  }

  long endTime = System.currentTimeMillis();

  System.out.println("function 4 use time: " + (endTime - startTime)

  + "ms");

  }

  public static void main(String[] args) {

  TestEmptyString test = new TestEmptyString();

  test.function1();

  test.function2();

  test.function3();

  test.function4();

  }

  注意:s == null 是有必要存在的.

  如果 String 类型为 null, 而去进行 equals(String) 或 length() 等操作会抛出java.lang.NullPointerException.

  并且s==null 的顺序必须出现在前面.不然同样会抛出java.lang.NullPointerException.

  如下代码:

  Java代码

  String str= = null;

  if(str=.equals("") || str= == null){//会抛出异常

  System.out.println("success");

  }

  // "".equales(str);后置确保不会遇null报错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: