繁体   English   中英

无法掌握 java 中的构造函数和类(初始化对象)

[英]Unable to master constructors and classes in java (initializing objects)

有一个名为 PageInfo 的 class 是这样的:

我假设 arrays 的最大尺寸为 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;
        }
    }

并且有一个帖子 class 像:

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

我想用构造函数声明一个用户,例如:

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]);

“getPostLength”效果很好。 但是当“GetFollowingLength”返回 0 时。为什么? 以及如何解决? 如何在项目后期向 allusers[x] 添加“关注”?

似乎“以下内容”尚未初始化,仍然是 Null。 我怎样才能正确初始化它们?

我认为您缺少的是在执行“new PageInfo [5]”或类似操作时使用 null 值初始化数组。 所以以下被初始化为一个空数组(所有值都为空)。 与所有用户相同。 所以“allusers[0].followings[0] = allusers[1];” 在这里不做任何事情。 它只是将值设置为 null,它已经是。

我不知道你到底想达到什么目标,所以我不确定你如何改进你的代码。 一种方法是像这样初始化一个数组:

Foo array = new Foo[42];
for(int i=0; i&lt;array.length; i++
{
    array[i] = new Foo();
}

暂无
暂无

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

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