如何检查null元素,如果它是整数数组在Java中? [英] How to check null element if it is integer array in Java?

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

问题描述

我很新的Java和有一个问题在检查整数数组空元素。
我使用的Eclipse编辑器以及检查空元素的行是显示错误:

行抱怨:

 如果(A [I]!= NULL){

从Eclipse的错误信息:

 操作员!=未定义的参数类型(S)INT,空

在PHP中,这个工作没有任何问题,但在Java好像我不得不改变从整型数组类型对象,使该行不会抱怨(如下图所示)

 对象[] =一个新的对象[3];

所以我的问题是,如果我还是想声明为整型数组,仍然要检查空,
什么是语法呢?

code:

 公共无效测试(){
        INT []一个=新INT [3];
        的for(int i = 0; I<则为a.length;我++){
            如果(A [I]!= NULL){//这一行抱怨......
                的System.out.println(空!);
            }
        }
    }


解决方案

在Java中,一个 INT 是基本类型,不能。对象,然而,因此,如果你声明的对象引用,但不作对象存储为引用,引用将

整数都是围绕整数对象包装,这意味着它们可以

 公共无效测试(){
        整数[]一个=新的整数[3];
        的for(int i = 0; I<则为a.length;我++){
            如果(A [I]!= NULL){//现在应该编译
                的System.out.println(空!);
            }
        }
    }

I'm quite new to Java and having an issue checking null element in integer array. I'm using Eclipse for editor and the line that checks null element is showing error:

Line that complains:

if(a[i] != null) {

Error msg from Eclipse:

The operator != is undefined for the argument type(s) int, null

In PHP, this works without any problem but in Java it seems like I have to change the array type from integer to Object to make the line not complain (like below)

Object[] a = new Object[3];

So my question is if I still want to declare as integer array and still want to check null, what is the syntax for it?

Code:

public void test() {
        int[] a = new int[3];
        for(int i=0; i<a.length; i++) {
            if(a[i] != null) { //this line complains...
                System.out.println('null!');
            }
        }
    }

解决方案

In Java, an int is a primitive type and cannot be null. Objects, however, are stored as references, so if you declare an object reference but do not make a new object, the reference will be null.

Integers are object wrappers around ints, meaning they can be null.

public void test() {
        Integer[] a = new Integer[3];
        for(int i=0; i<a.length; i++) {
            if(a[i] != null) { //should now compile
                System.out.println('null!');
            }
        }
    }

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

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