[英]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<array.length; i++
{
array[i] = new Foo();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.