java object 是否为null,如何在Java中检查object是否为null?

博客探讨了在Java类中如何正确检查对象是否为空。原始代码中使用`this==null`来检查对象是否为空,但这种方法不适用于实例变量。建议将`char`类型改为`Character`对象,并通过`letter==null`来判断对象是否为空。此外,还提醒了默认构造函数的使用情况,指出在某些情况下不需要显式调用`super()`。
摘要由CSDN通过智能技术生成

What is the best way to check if a position is occupied or not? I don't think I should be using "this==null"...

class Cell {

int column;

int row;

char letter;

public Cell(int column, int row, char letter) {

super();

this.column = column;

this.row = row;

this.letter = letter;

}

public boolean isEmpty() {

if (this==null) return true;

else return false;

}

}

解决方案

I'm going to assume that the char is the content of your Cell and you want to check if that content is null.

First, this cannot ever be null. this is the current object, and therefore is always exists.

You are using a char - as this is a primitive is also cannot be null. Change that to the object wrapper and check that for null

class Cell {

int column;

int row;

Character letter;

public Cell(int column, int row, Character letter) {

this.column = column;

this.row = row;

this.letter = letter;

}

public boolean isEmpty() {

return letter == null;

}

}

Another note is that the superclass constructor is always called by default, there is no reason to call super().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值