qttsuki_
qttsuki_

Reputation: 5

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!

Upvotes: 0

Views: 47

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339432

The Answer by Pieter12345 is correct and smart.

Here is a table graphic I made to assist you in choosing an implementation of Map from among those bundled with Java. All of these support the operations seen in that other Answer.

Third-parties produce may produce Map implementations as well, such as Eclipse Collections or Google Guava.

enter image description here

Upvotes: 0

Pieter12345
Pieter12345

Reputation: 1789

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

Upvotes: 1

Related Questions