简体   繁体   中英

How to temporarily initialize an object to avoid NullPointerException in java?

I got a Post class which will contain some posts of a page!

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.

For example i have 2 posts but my array of posts has a size of 5.

Post[] postArray = new Post[5];

I specify used posts with "isValid".

Then how can i don't get a NullPointerException when i'm counting valid posts size?

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:

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. You can't call a method or access a property of a null object.

Wrap the existing if statement with a null check.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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