3

There is a class called PageInfo which is like this:

I assume the max size of arrays is 5.

public static class PageInfo {
        String username;
        PageInfo[] followings;
        Post posts[];

        PageInfo (String username,PageInfo[] followings,Post[] posts) {
            this.username = username;      
            this.followings = followings;    
            this.posts = posts;
        }

        public int getPostLength () {
            int cnt = 0;
            for (int i = 0; i < 5; i++) {
                if (posts[i] != null )
                    cnt++;
            }
            return cnt;
        }

        public int getFollowingLength () {
            int cnt = 0;
            for (int i = 0; i < 5; i++) {
                if (followings[i] != null )
                    cnt++;
            }
            return cnt;
        }
    }

and there is a Post class like:

public static class Post {
        String cation;
        int id;
        PageInfo[] usersLiked;


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

I want to declare a user with constructor like:

PageInfo[] allusers = new PageInfo[5];

allusers[0] = new PageInfo("John", "54321", new PageInfo[5], new Post[5]);
allusers[0].followings[0] = allusers[1];
allusers[0].posts[0] = new Post("John Post", 100, new PageInfo[5]);

The "getPostLength" works well. but when "GetFollowingLength" returns me 0. why? and how to fix it? how can i add "followings" to the allusers[x] later in the project?

It seems that "followings" hasn't been initialized yet and the're still Null. how can i properly initalize them?

Behnawwm
  • 121
  • 2
  • 9
  • 1
    `allusers[0].followings[0]` is initially null; `allusers[1]` is null, so after `allusers[0].followings[0] = allusers[1]`, it's still null. [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – Andy Turner Apr 15 '20 at 13:14
  • Just a hint: if this is about pagination, you might be better off with using just a double linked list (LinkedList in Java) instead of an array. – maio290 Apr 15 '20 at 13:15

1 Answers1

2

I think what you're missing is that an array is initialized with null values when you do "new PageInfo[5]" or something similar. So followings is initialized as an empty array (all values null). Same with allusers. So "allusers[0].followings[0] = allusers[1];" does not do anything here. It just sets the value to null, which it already is.

I don't know what exactly you want to achieve, so I'm not sure how you could improve your code. One way could be to initialize an array like this:

Foo array = new Foo[42];
for(int i=0; i&lt;array.length; i++
{
    array[i] = new Foo();
}
tobi
  • 1,205
  • 2
  • 8
  • 8