Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

java - difference between natural ordering and total ordering

I happen to come across many statements like comparable is used when natural ordering is required while sorting an array or collection and comparator for total ordering.

The version you may have heard could be same or different with the same meaning but ultimately its one of the distinguishing factors between the two(comparator and comparable interfaces).

But, I couldn't find a difference between the two types of ordering anywhere. I'd appreciate if someone could explain it with a good example :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Total ordering means all values can be compared to all other values. For example, if you have a collection of BigDecimal and String there is no natural total order (but you could invent one)

In Java, the Natural order is defined as the ordering provided by the JVM. This might not match what a people might believe is the natural order. e.g. Strings are sorted ASCIIbetically. Meaning an uppercase Z comes before a lowercase a and 10 is before 2

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...