Metoda compareTo dlaczego taki wynik się pojawia przy porównaniu Stringów

0

Witam Forumowiczów
Moje pytanie kieruje odnośnie klasy compareTo. Otóż rozumiem w jaki sposób to mniej więcej działa. Poniżej kod do tego problemu.

public class Test2 {
	public static void main(String[] args) {
		
		String s1 = "Welcome to Java";
		String s2 = "Programming is fun";
		String s3 = "Welcome to Java";
		
		System.out.println(s1.compareTo(s2));
		System.out.println(s2.compareTo(s3));
		System.out.println(s1.compareTo(s3));
	}
}

Rozumiem kwestię znaków z czego to wynika. Tj.:

  • przyjmuje liczbę większą od 0 kiedy pierwsze porównanie litery z drugą literą nie są w chronologii alfabetycznej (najpierw jest litera W ze zmiennej s1 która jest porównywana z pierwszą literą P ze zmiennej s2, litery w kolejności W-P nie odpowiadają chronologii alfabetu, dlatego wynik jest większy od 0)
  • przyjmuje liczbę mniejszą od 0 kiedy pierwsze porównanie litery z drugą literą jest w chronologii alfabetycznej (najpierw jest litera P ze zmiennej s2 która jest porównywana z pierwszą literą W ze zmiennej s3, litery w kolejności P-W odpowiadają chronologii alfabetu, dlatego wynik jest mniejszy od 0)
  • przyjmuje 0 kiedy oba Stringi są takie same

Problem w tym że nie rozumiem co mi mówią te siódemki z pierwszych dwóch instrukcji System.out.println(...); Możecie mi wytłumaczyć o czym one świadczą?

W pewnym sensie mam wrażenie, że chodzi o ilość sprawdzanych liter do momentu gdy nie jest przerwana białym znakiem. Ale nie mam pewności dlatego pytanie kieruje do Was.
Pozdrawiam
Konrad

1

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()

0

dziękuje za szybką odpowiedz, teraz już wiem :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1