如何在Java中检查object是否为null? [英] How to check if object is null in Java?

查看:706
本文介绍了如何在Java中检查object是否为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查职位是否被占用的最佳方法是什么?我不认为我应该使用 this == null ...

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我会假设 char 是您的 Cell 的内容,并且您想检查该内容是否 null

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

首先,永远不能是 null 是当前对象,因此始终存在。

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

您正在使用 char -因为这是一个原语,也不能为 null 。将其更改为对象包装,并检查 null

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;
    }
}

另一个要注意的是,超类构造函数总是由默认情况下,没有理由调用 super()

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

这篇关于如何在Java中检查object是否为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆