What is the practical use of the Java compareTo method?

In the Java textbook that I am studying, he says that “lexicographical ordering” is used for the “whole”. I understand how it works, but in what specific way is it used in programming?

+3
source share
7 answers

All built-in sorting methods use it when sorting non-primitives.

+9
source

Let's say you wanted to sort the glasses of water, the objects themselves are called Glass.

Now let's say that a Glasscan have the height and amount of water that it holds.

, Glasses. ?

, compareTo. , , . , , .

+3

, , , , , , re .

+2

String s, . < 0, = 0 > 0 , String .

+1

compareTo() - - Java.

, , <, == > . ( , , equals() moreThan() .)

, . :

  • , TreeSet TreeMap ( ).

  • .

  • , . , .

+1

compareTo int, , , .

, Comparable . Java, , (String, Double, BigInteger,...).

compareTo :

  • x.compareTo(y) - of y.compareTo(x), x y
  • x.compareTo(y) > 0 y.compareTo(z) > 0, x.compareTo(z) > 0.
  • equals() .

:
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
http://www.javapractices.com/topic/TopicAction.do?Id=10

+1

This most common use is a comparison function when sorting a list of strings. One call compareToindicates whether one line goes before another, after another, or the same as on the other line.

0
source

Source: https://habr.com/ru/post/1713267/


All Articles