如何临时初始化对象以避免Java中的NullPointerException?

问题描述 投票:0回答:2

我有一个Post类,其中将包含页面的一些帖子!

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

我定义了一个帖子数组,其中一些帖子尚未实际使用,因此以后将使用它们。

例如,我有2个帖子,但我的帖子数组大小为5。

Post[] postArray = new Post[5];

我用“ isValid”指定使用过的帖子。

然后,当我计算有效的帖子大小时,如何不获得NullPointerException?

public int getPostLength () {
            int cnt = 0;
            for (int i = 0; i < 5; i++) {           // 5 : arraysize
                if (postArray[i].isValid == true)
                    cnt++;
            }
            return cnt;
        }
java nullpointerexception
2个回答
1
投票
    public int getPostLength () {
        int cnt = 0;
        for (int i = 0; i < 5; i++) {           // 5 : arraysize
            if (postArray[i] != null && postArray[i].isValid)
                cnt++;
        }
        return cnt;
    }

0
投票

您可以通过java流实现它:

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

© www.soinside.com 2019 - 2024. All rights reserved.