我是Java新手,需要在方法返回null和引用变量时找出过程。当方法返回null时会发生什么
下面是该方法的代码:
public Lot getLot(int lotNumber)
{
if((lotNumber >= 1) && (lotNumber < nextLotNumber)) {
// The number seems to be reasonable.
Lot selectedLot = lots.get(lotNumber - 1);
// Include a confidence check to be sure we have the
// right lot.
if(selectedLot.getNumber() != lotNumber) {
System.out.println("Internal error: Lot number " +
selectedLot.getNumber() +
" was returned instead of " +
lotNumber);
// Don't return an invalid lot.
selectedLot = null;
}
return selectedLot;
}
else {
System.out.println("Lot number: " + lotNumber +
" does not exist.");
return null;
}
}
当方法返回null和参考变量,而具有类数据类型会发生什么?
请用简单的语言解释。
如果您不小心,最终可能会得到NPE ..:P。没什么特别的事返回'null'就像返回对其他实例的引用。 – TheLostMind 2014-11-03 10:32:33