Igor
Igor

Reputation: 1640

Is sorting and copying objects the best way to do this?

I decided to do server-side sorting. I have a HashMap with Objects (key is a String, value is an ItemDTO). These are loaded statically upon server start.

For every character (CharacterDTO) that has an amount of items (in this case ItemOnCharacterDTO) I need to be able to sort stuff. So my client sends a request for sorting the objects as well as some filter-data. What I now want to do is:

  1. get the full ItemDTOs based on the IDs saved in ItemOnCharacterDTOs
  2. add those ItemDTOs into a list
  3. sort the ItemDTOs inside that list (probably using a Comparator)
  4. create an Array of IDs (it corresponds to the sequence of the list of ItemDTOs after the sorting)
  5. discard the list of ItemDTOs that I've previously created, since I got the correct order after sorting already

My question is now: do I need to copy the ItemDTOs before adding them to the list in order to not interfere with several sortings going on at the same time?

I do change the order of ItemDTOs within the newly created list of ItemDTOs (step 2 above), but I don't change the ItemDTOs themselves (hence they are static and within the HashMap I mentioned at the beginning).

Thank you for your help in advance!

Upvotes: 0

Views: 72

Answers (1)

brain
brain

Reputation: 5546

You only need to copy the individual objects if they are mutable i.e. if they might be changed in a way that would effect the sort order or filtering. In Java an array of Objects is actually an array of references to objects on the heap, so moving the references in the array has no effect on the underlying objects.

Upvotes: 2

Related Questions