0

I've got a Java program which stores a list of cricket club players using an arraylist. In the club class I have a static field which keeps track of of how many players are registered in the club. Also I assign a player ID to the static field so that each time a player is added he gets an ID. This is how

id = regPlayer++;

regPlayer is the static field, which is initialized as 1

The problem I'm having is that if I want to remove a player from the arraylist I can't seem to be able to update the IDs. For example if I have four players they will have the following IDs before I remove any of them:

Player 1 ID = 1
Player 2 ID = 2
Player 3 ID = 3
Player 4 ID = 4

If I remove Player 2 I now want the third player to have ID 2 and the fourth player to have ID 3, like that:

Player 1 = 1
Player 3 = 2
Player 4 = 3

Is there a way of achieving this with arraylists and how?

1
  • If the playerId is bound to the index of the player in the array you could just use the element's index as playerId. Commented Apr 18, 2012 at 18:21

2 Answers 2

2

IDs should generally be immutable. You should not be shifting IDs, simply because you want to make the ID double as an index into the list. So don't update the IDs. That is about the same as trying to update someone's Social Security Number... bad idea.

I can only guess that you want the ID to reflect the index position so that you can somehow quickly know which position a given Object occupies. If that's the case, just use: List.indexOf(Object) to look up the position, rather than counting on the ID to also represent the position.

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

3 Comments

Yep, maybe OP can explain why they want to reassign IDs but in general it's a bad idea.
Hmm I guess that's a logical answer. I've just been indecisive about whether to shift the IDs or not. I guess I'll just leave it unique for each player then. Thanks
You're welcome. And since you are new here, the way this site works is that if you ask a question and like one or more answers that you get, you can "upvote" them. And after a period of time, if there is one particular answer that best helped you, you can select that answer by clicking on the checkmark next to it. Both actions award the answerer with "reputation points" -- a cheap thrill, but I'll take what I can get ;-)
0

You need to assign the ID based on the index of the array list. It can be re-assigned while you remove the element and the index gets reorganized.

Comments

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.