Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

java - Is there a way to create an ArrayList under certain circumstances?

I'm sorry if the question is phrased weirdly, but I wasn't quite sure how to fit it into the title space. I'm making a mini messaging program in which users create and log into accounts and send and receive messages. Is there a way to create an ArrayList of the user's messages when they create an account? All of the usernames are in another ArrayList, so maybe it can create one for every addition? I have the passwords and usernames in two different lists linked by position, so that could work too if it's even possible.

PS - I also need to be able to pull out and match the ArrayList to usernames, but that will come later.

I can clarify in the comments and show my code if you need it.

Thanks!

question from:https://stackoverflow.com/questions/65848754/is-there-a-way-to-create-an-arraylist-under-certain-circumstances

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like you are looking for a data structure to store a list of messages per user. You can use a Map<User, List<Message> for this. When loading/adding a User, you can create an empty ArrayList<Message> and put it into the map for later use.

// Create map.
Map<User, List<Message>> userMessageMap = new HashMap<>();

// Insert new list for new user.
userMessageMap.put(user, new ArrayList<>());

// Insert message for existing user.
userMessageMap.get(user).add(message);

// Get all messages for an existing user.
List<Message> messages = userMessageMap.get(user);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...