我一直在调试this LeetCode problem about Twitter Design的解决方案。我仍然在调试代码,但我主要担心的是当我尝试在静态HashMap中将Integers推送到Stack时得到的NullPointerException。
这是我的代码:
import java.util.Stack;
import java.util.HashMap;
import java.util.HashSet;
public class Twitter {
private static HashMap<Integer, Stack<Integer>> newsFeed;
private HashMap<Integer, HashSet<Integer>> followList;
/** Initialize your data structure here. */
public Twitter() {
//Holds a userId as a key, with a Stack of tweets acting as a newfeed.
newsFeed = new HashMap<Integer, Stack<Integer>>();
//Holds a userId as a key, with a HashSet of userIds in the user's follow list
followList = new HashMap<Integer, HashSet<Integer>>();
}
/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
/** When a user tweets, the tweet is seen by the user and all the user's followers; therefore, each tweet posted requires an update to the newsfeed Stack of the user and all their followers. */
Stack<Integer> userFeed = newsFeed.get(userId);
userFeed.push(new Integer(tweetId));
newsFeed.put(userId, userFeed);
postToAllFollowers(userId, tweetId);
}
private void postToAllFollowers(int userId, int tweetId){
HashSet<Integer> set = followList.get(userId);
for(Integer followerId : set){
Stack<Integer> followerFeed = newsFeed.get(followerId);
followerFeed.push(new Integer(tweetId));
newsFeed.put(followerId, followerFeed);
}
}
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
public List<Integer> getNewsFeed(int userId) {
if(!newsFeed.containsKey(userId)){
return null;
}
Stack<Integer> stack = newsFeed.get(userId);
return stackToListIn10(stack);
}
private List<Integer> stackToListIn10(Stack<Integer> stack){
List<Integer> timeLine = new ArrayList<Integer>();
while((timeLine.size() != 10) || (!stack.isEmpty())){
timeLine.add(stack.pop());
}
return timeLine;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
public void follow(int followerId, int followeeId) {
HashSet<Integer> set = followList.get(followerId);
set.add(followeeId);
followList.put(followerId, set);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
public void unfollow(int followerId, int followeeId) {
HashSet<Integer> set = followList.get(followerId);
set.remove(followeeId);
followList.put(followerId, set);
}
}
/**
* Your Twitter object will be instantiated and called as such:
* Twitter obj = new Twitter();
* obj.postTweet(userId,tweetId);
* List<Integer> param_2 = obj.getNewsFeed(userId);
* obj.follow(followerId,followeeId);
* obj.unfollow(followerId,followeeId);
*/
LeetCode给出了以下错误:第20行:java.lang.NullPointerException
对此有何见解?我没有在StackOverflow上看到这个问题,所以我认为它不是重复的