null的理解

本文通过一个Java示例程序详细解释了null与空字符串()的区别,展示了如何正确判断这两种情况,并强调了在使用ArrayList和Iterator时进行null判断的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

null翻译过来是“空”
""翻译过来是零长度字符串
一个什么都不是,一个是String类实例
  1. import java.util.ArrayList;   
  2.   
  3.   
  4. public class testNull   
  5. {   
  6.     /**  
  7.      * @param args  
  8.      */  
  9.     public static void main ( String[] args )   
  10.     {   
  11.   
  12.         testNull a=new testNull();   
  13.         ArrayList<String> l=a.getTest("");   
  14.   
  15.         if(l==null)   
  16.         {   
  17.             System.out.println("is null");   
  18.         }   
  19.         else  
  20.         {   
  21.             System.out.println("is not null");   
  22.         }   
  23.     }   
  24.   
  25.     public ArrayList<String> getTest(String item)   
  26.     {   
  27.         ArrayList<String> list=new ArrayList<String>();   
  28.         if(item==null || "".equals(item))   
  29.         {   
  30.             return null;   
  31.         }   
  32.         else  
  33.         {   
  34.             return list;   
  35.         }   
  36.     }   
  37. }  
import java.util.ArrayList;


public class testNull
{
	/**
	 * @param args
	 */
	public static void main ( String[] args )
	{

		testNull a=new testNull();
		ArrayList<String> l=a.getTest("");

		if(l==null)
		{
			System.out.println("is null");
		}
		else
		{
			System.out.println("is not null");
		}
	}

	public ArrayList<String> getTest(String item)
	{
		ArrayList<String> list=new ArrayList<String>();
		if(item==null || "".equals(item))
		{
			return null;
		}
		else
		{
			return list;
		}
	}
}


二。讲解
   上述的代码中有两个地方可以测试。
    1.在public ArrayList<String> getTest(String item)方法中,如果if(item==null || "".equals(item))改成if(item==null )则会输出"is not null"
如果加上,则会输出"is null",这说明null和""是不一样的。

    2.if(item==null)则会输出"is not null",但为什么会输出不是空呢?因为这句代码“ArrayList<String> list=new ArrayList<String>();”,事实上,这句代码的意思已经代表在内存区域分配了内存,所以return list是不为空(null)的。但反过来说,如果把ArrayList<String> list=new ArrayList<String>();改成ArrayList<String> list=null;的话则会输出"is null"

   3.我们在用ArrayList和Iterator的时候,希望注意null的判断。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值