Does Collections.sort consider an index among related items? (Sort stability)

For example, if I am sorting List<Individual>

with 10 people Individual::Age

, and I enter Alice (3), Bob (5) and Charles (3), the output will be Alice (3), Charles (3), Bob (5), or perhaps Alice and Charles were swapped so that they were displayed in a different sequence than those entered?

Edit:
It seems that his property has its own name: https://en.wikipedia.org/wiki/Sorting_algorithm#Stability

+3


source to share


3 answers


To quote the documentation :

This type is guaranteed to be stable: equal elements will not be reordered by sorting.



For this purpose, Alice and Charles are equal (since they are the same age). The call is sort

guaranteed to preserve their relative order and Alice will appear in front of Charles.

+8


source


It depends on the stability of the sorting algorithm: see wikipedia page



Depends on JDK implementation

+1


source


It totally depends on how we implement our comparison class. If you are only comparing age, then the order will be the same as inserted (like List, using merge sort), or if you are comparing age and name, then it will be in dictionary order.

+1


source







All Articles