简体   繁体   English

如何临时初始化 object 以避免 java 中的 NullPointerException?

[英]How to temporarily initialize an object to avoid NullPointerException in java?

I got a Post class which will contain some posts of a page!我得到了一个帖子 class ,其中将包含一个页面的一些帖子!

public static class Post {
        String cation;
        int id;
        PageInfo[] usersLiked;
        boolean isValid = false;

        Post (String caption, int id, PageInfo[] usersLiked) {
            this.cation = caption;
            this.id = id;
            this.usersLiked = usersLiked;
        }
    }

I defined an array of Posts which some of them are not actually used yet and they're made to be used later.我定义了一个 Posts 数组,其中一些还没有实际使用,它们将在以后使用。

For example i have 2 posts but my array of posts has a size of 5.例如,我有 2 个帖子,但我的帖子数组的大小为 5。

Post[] postArray = new Post[5];

I specify used posts with "isValid".我用“isValid”指定使用过的帖子。

Then how can i don't get a NullPointerException when i'm counting valid posts size?那么当我计算有效帖子大小时,我怎么能不得到 NullPointerException 呢?

public int getPostLength () {
            int cnt = 0;
            for (int i = 0; i < 5; i++) {           // 5 : arraysize
                if (postArray[i].isValid == true)
                    cnt++;
            }
            return cnt;
        }
    public int getPostLength () {
        int cnt = 0;
        for (int i = 0; i < postArray.length; i++) {
            if (postArray[i] != null && postArray[i].isValid)
                cnt++;
        }
        return cnt;
    }

You could do it via java streams:您可以通过 java 流来做到这一点:

long cnt= Arrays.stream(postArray).filter(Objects::nonNull).filter(Post::isValid).count()

If the postArray has only two post element, then the if statement will cause a null pointer exception.如果 postArray 只有两个 post 元素,那么 if 语句将导致 null 指针异常。 You can't call a method or access a property of a null object.您不能调用 null object 的方法或访问属性。

Wrap the existing if statement with a null check.用 null 检查包装现有的 if 语句。

public int getPostLength () {
            int cnt = 0;
            for (int i = 0; i < 5; i++) { 
                if (postArray[I] != null) {
                    if (postArray[i].isValid == true)
                        cnt++;
                }          
            }
            return cnt;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM