1

In Java, I'm trying to store a User object in an ArrayList and before storing / adding it - I'm asking the index number where this object should be stored in. When he enters the Index Number, I want to check if that Index is empty i.e no other User object is stored on that index - if it's empty, the new User will be added and if it's already occupied, I'll ask the user to enter a valid Index number again..

So the question is - how do I check if a specific Index in an ArrayList is empty?

I'm aware that there exists this method ArrayList.contains(Object e) but the issue here is, I want to see if a specific INDEX exists, not if an OBJECT exists.. So kindly let me know how I can achieve that, Thank You.

2 Answers 2

2

I think you misunderstood how Lists (or ArrayLists in this case) works. A list can't have empty slots in it. When a List have 1 element, it will always have index 0. If there are 3 elements they have indicies 0, 1 and 2. Then, if you remove element with index 1 from that list, it gets reorganized, and have elements at positions 0 and 1.

If you want to keep indecies of elements you could either use a simple array of Objects, User[], or a map of indecies and objects assigned to them, Map<Integer, User>.

Sign up to request clarification or add additional context in comments.

Comments

0

You can check it by:

boolean exists = index < list.size()

method, if the index >= size, then it doesn't exits.

3 Comments

Keep in mind that you can't add element at index > list.size(), not with add(int index, E element)
I've a question - if the previous user is added at 5th index, won't the size be 1? So the 2nd user will still be able to add another user at 5th index - or am I misunderstanding something here?
You can't add an element at an index that is not <= the size of the list. Thus, there's no way to add an element at index 5 if the list is empty; the only place you can add in an empty list is at index 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.