简体   繁体   中英

How to check if a certain Index exists in an ArrayList in Java

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 ie 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.

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> .

You can check it by:

boolean exists = index < list.size()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM