简体   繁体   中英

Java Collections Sorting Hypothetical

I am currently a computer science major and am taking a course in advanced java programming. My question today is if you have two identical lists, lets call them list1 and list2, and you invoke Collections.sort(list1) and Collections.sort(list2), is it possible for these two lists to be different after invoking this? My textbook says that it is possible, while my professor says it isn't. Can someone please clarify this for me?

If we consider the obvious case such as sorting List<Integer> , then no it's not possible. If you're sorting two identical lists, they should be properly sorted of course.

However since Collections.sort() requires that the objects being sorted are Comparable , you can always implement Comparable poorly. For example you could have compareTo() return a random value (or the time of day, or anything not related to the object actually being sorted), and you wouldn't have any idea how they would be sorted.

Collections.sort() can notice if compareTo() is implemented wrong and will throw an exception saying Comparison method violates its general contract! . However it's not 100% guaranteed to notice this, so technically it is possible to have 2 identical collections sorted in different ways.

As equality is defined by Object.equals() , but comparison is defined by Comparable.compareTo() or Comparator.compare() , like the javadoc says:

It is strongly recommended (though not required) that natural orderings be consistent with equals.

Otherwise it is possible that equal elements are sorted differently.

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