logo

Java-merkkijono vertaa()

The Java-merkkijonoluokka vertaa() menetelmä vertaa annettua merkkijonoa nykyiseen merkkijonoon leksikografisesti. Se palauttaa positiivisen luvun, negatiivisen luvun tai 0:n.

Se vertaa merkkijonoja kunkin merkkijonon Unicode-arvon perusteella.

Jos ensimmäinen merkkijono on leksikografisesti suurempi kuin toinen merkkijono, se palauttaa positiivisen luvun (merkkien arvon eron). Jos ensimmäinen merkkijono on leksikografisesti pienempi kuin toinen merkkijono, se palauttaa negatiivisen luvun, ja jos ensimmäinen merkkijono on leksikografisesti yhtä suuri kuin toinen merkkijono, se palauttaa 0:n.

 if s1 &gt; s2, it returns positive number if s1 <s2, 0 it returns negative number if s1="=" s2, < pre> <h3>Syntax</h3> <pre> public int compareTo(String anotherString) </pre> <p>The method accepts a parameter of type String that is to be compared with the current string.</p> <p>It returns an integer value. It throws the following two exceptions:</p> <p> <strong>ClassCastException:</strong> If this object cannot get compared with the specified object.</p> <p> <strong>NullPointerException:</strong> If the specified object is null.</p> <h2>Internal implementation</h2> <pre> int compareTo(String anotherString) { int length1 = value.length; int length2 = anotherString.value.length; int limit = Math.min(length1, length2); char v1[] = value; char v2[] = anotherString.value; int i = 0; while (i <limit) { char ch1="v1[i];" ch2="v2[i];" if (ch1 !="ch2)" return - ch2; } i++; length1 length2; < pre> <h2>Java String compareTo() Method Example</h2> <p> <strong>FileName:</strong> CompareToExample.java</p> <pre> public class CompareToExample{ public static void main(String args[]){ String s1=&apos;hello&apos;; String s2=&apos;hello&apos;; String s3=&apos;meklo&apos;; String s4=&apos;hemlo&apos;; String s5=&apos;flag&apos;; System.out.println(s1.compareTo(s2));//0 because both are equal System.out.println(s1.compareTo(s3));//-5 because &apos;h&apos; is 5 times lower than &apos;m&apos; System.out.println(s1.compareTo(s4));//-1 because &apos;l&apos; is 1 times lower than &apos;m&apos; System.out.println(s1.compareTo(s5));//2 because &apos;h&apos; is 2 times greater than &apos;f&apos; }} </pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> 0 -5 -1 2 </pre> <h2>Java String compareTo(): empty string</h2> <p>When we compare two strings in which either first or second string is empty, the method returns the length of the string. So, there may be two scenarios:</p> <ul> <li>If <strong>first</strong> string is an empty string, the method returns a <strong>negative</strong> </li> <li>If <strong>second</strong> string is an empty string, the method returns a <strong>positive</strong> number that is the length of the first string.</li> </ul> <p> <strong>FileName:</strong> CompareToExample2.java</p> <pre> public class CompareToExample2{ public static void main(String args[]){ String s1=&apos;hello&apos;; String s2=&apos;&apos;; String s3=&apos;me&apos;; System.out.println(s1.compareTo(s2)); System.out.println(s2.compareTo(s3)); }} </pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> 5 -2 </pre> <h3>Java String compareTo(): case sensitive</h3> <p>To check whether the compareTo() method considers the case sensitiveness of characters or not, we will make the comparison between two strings that contain the same letters in the same sequence.</p> <p>Suppose, a string having letters in uppercase, and the second string having the letters in lowercase. On comparing these two string, if the outcome is 0, then the compareTo() method does not consider the case sensitiveness of characters; otherwise, the method considers the case sensitiveness of characters.</p> <p> <strong>FileName:</strong> CompareToExample3.java</p> <pre> public class CompareToExample3 { // main method public static void main(String argvs[]) { // input string in uppercase String st1 = new String(&apos;INDIA IS MY COUNTRY&apos;); // input string in lowercase String st2 = new String(&apos;india is my country&apos;); System.out.println(st1.compareTo(st2)); } } </pre> <p> <strong>Output:</strong> </p> <pre> -32 </pre> <p> <strong>Conclusion:</strong> It is obvious by looking at the output that the outcome is not equal to zero. Hence, the compareTo() method takes care of the case sensitiveness of characters.</p> <h3>Java String compareTo(): ClassCastException</h3> <p>The <strong>ClassCastException</strong> is thrown when objects of incompatible types get compared. In the following example, we are comparing an object of the ArrayList (al) with a string literal (&apos;Sehwag&apos;).</p> <p> <strong>FileName:</strong> CompareToExample4.java</p> <pre> // import statement import java.util.*; class Players { private String name; // constructor of the class public Players(String str) { name = str; } } public class CompareToExample4 { // main method public static void main(String[] args) { Players ronaldo = new Players(&apos;Ronaldo&apos;); Players sachin = new Players(&apos;Sachin&apos;); Players messi = new Players(&apos;Messi&apos;); ArrayList al = new ArrayList(); al.add(ronaldo); al.add(sachin); al.add(messi); // performing binary search on the list al Collections.binarySearch(al, &apos;Sehwag&apos;, null); } } </pre> <p> <strong>Output:</strong> </p> <pre> Exception in thread &apos;main&apos; java.lang.ClassCastException: class Players cannot be cast to class java.lang.Comparable </pre> <h3>Java String compareTo(): NullPointerException</h3> <p>The NullPointerException is thrown when a null object invokes the compareTo() method. Observe the following example.</p> <p> <strong>FileName:</strong> CompareToExample5.java</p> <pre> public class CompareToExample5 { // main method public static void main(String[] args) { String str = null; // null is invoking the compareTo method. Hence, the NullPointerException // will be raised int no = str.compareTo(&apos;India is my country.&apos;); System.out.println(no); } } </pre> <p> <strong>Output:</strong> </p> <pre> Exception in thread &apos;main&apos; java.lang.NullPointerException at CompareToExample5.main(CompareToExample5.java:9) </pre> <hr></limit)></pre></s2,>

Menetelmä hyväksyy parametrin, jonka tyyppi on String, jota verrataan nykyiseen merkkijonoon.

Se palauttaa kokonaisluvun arvon. Se antaa seuraavat kaksi poikkeusta:

ClassCastException: Jos tätä objektia ei voi verrata määritettyyn objektiin.

NullPointerException: Jos määritetty objekti on tyhjä.

tyhjä lista java

Sisäinen toteutus

 int compareTo(String anotherString) { int length1 = value.length; int length2 = anotherString.value.length; int limit = Math.min(length1, length2); char v1[] = value; char v2[] = anotherString.value; int i = 0; while (i <limit) { char ch1="v1[i];" ch2="v2[i];" if (ch1 !="ch2)" return - ch2; } i++; length1 length2; < pre> <h2>Java String compareTo() Method Example</h2> <p> <strong>FileName:</strong> CompareToExample.java</p> <pre> public class CompareToExample{ public static void main(String args[]){ String s1=&apos;hello&apos;; String s2=&apos;hello&apos;; String s3=&apos;meklo&apos;; String s4=&apos;hemlo&apos;; String s5=&apos;flag&apos;; System.out.println(s1.compareTo(s2));//0 because both are equal System.out.println(s1.compareTo(s3));//-5 because &apos;h&apos; is 5 times lower than &apos;m&apos; System.out.println(s1.compareTo(s4));//-1 because &apos;l&apos; is 1 times lower than &apos;m&apos; System.out.println(s1.compareTo(s5));//2 because &apos;h&apos; is 2 times greater than &apos;f&apos; }} </pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> 0 -5 -1 2 </pre> <h2>Java String compareTo(): empty string</h2> <p>When we compare two strings in which either first or second string is empty, the method returns the length of the string. So, there may be two scenarios:</p> <ul> <li>If <strong>first</strong> string is an empty string, the method returns a <strong>negative</strong> </li> <li>If <strong>second</strong> string is an empty string, the method returns a <strong>positive</strong> number that is the length of the first string.</li> </ul> <p> <strong>FileName:</strong> CompareToExample2.java</p> <pre> public class CompareToExample2{ public static void main(String args[]){ String s1=&apos;hello&apos;; String s2=&apos;&apos;; String s3=&apos;me&apos;; System.out.println(s1.compareTo(s2)); System.out.println(s2.compareTo(s3)); }} </pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> 5 -2 </pre> <h3>Java String compareTo(): case sensitive</h3> <p>To check whether the compareTo() method considers the case sensitiveness of characters or not, we will make the comparison between two strings that contain the same letters in the same sequence.</p> <p>Suppose, a string having letters in uppercase, and the second string having the letters in lowercase. On comparing these two string, if the outcome is 0, then the compareTo() method does not consider the case sensitiveness of characters; otherwise, the method considers the case sensitiveness of characters.</p> <p> <strong>FileName:</strong> CompareToExample3.java</p> <pre> public class CompareToExample3 { // main method public static void main(String argvs[]) { // input string in uppercase String st1 = new String(&apos;INDIA IS MY COUNTRY&apos;); // input string in lowercase String st2 = new String(&apos;india is my country&apos;); System.out.println(st1.compareTo(st2)); } } </pre> <p> <strong>Output:</strong> </p> <pre> -32 </pre> <p> <strong>Conclusion:</strong> It is obvious by looking at the output that the outcome is not equal to zero. Hence, the compareTo() method takes care of the case sensitiveness of characters.</p> <h3>Java String compareTo(): ClassCastException</h3> <p>The <strong>ClassCastException</strong> is thrown when objects of incompatible types get compared. In the following example, we are comparing an object of the ArrayList (al) with a string literal (&apos;Sehwag&apos;).</p> <p> <strong>FileName:</strong> CompareToExample4.java</p> <pre> // import statement import java.util.*; class Players { private String name; // constructor of the class public Players(String str) { name = str; } } public class CompareToExample4 { // main method public static void main(String[] args) { Players ronaldo = new Players(&apos;Ronaldo&apos;); Players sachin = new Players(&apos;Sachin&apos;); Players messi = new Players(&apos;Messi&apos;); ArrayList al = new ArrayList(); al.add(ronaldo); al.add(sachin); al.add(messi); // performing binary search on the list al Collections.binarySearch(al, &apos;Sehwag&apos;, null); } } </pre> <p> <strong>Output:</strong> </p> <pre> Exception in thread &apos;main&apos; java.lang.ClassCastException: class Players cannot be cast to class java.lang.Comparable </pre> <h3>Java String compareTo(): NullPointerException</h3> <p>The NullPointerException is thrown when a null object invokes the compareTo() method. Observe the following example.</p> <p> <strong>FileName:</strong> CompareToExample5.java</p> <pre> public class CompareToExample5 { // main method public static void main(String[] args) { String str = null; // null is invoking the compareTo method. Hence, the NullPointerException // will be raised int no = str.compareTo(&apos;India is my country.&apos;); System.out.println(no); } } </pre> <p> <strong>Output:</strong> </p> <pre> Exception in thread &apos;main&apos; java.lang.NullPointerException at CompareToExample5.main(CompareToExample5.java:9) </pre> <hr></limit)>
Testaa nyt

Lähtö:

 0 -5 -1 2 

Java-merkkijono vertailuTo(): ​​tyhjä merkkijono

Kun vertaamme kahta merkkijonoa, joissa joko ensimmäinen tai toinen merkkijono on tyhjä, menetelmä palauttaa merkkijonon pituuden. Joten voi olla kaksi skenaariota:

  • Jos ensimmäinen merkkijono on tyhjä merkkijono, menetelmä palauttaa a negatiivinen
  • Jos toinen merkkijono on tyhjä merkkijono, menetelmä palauttaa a positiivinen numero, joka on ensimmäisen merkkijonon pituus.

Tiedoston nimi: VertaaEsimerkki2.java

 public class CompareToExample2{ public static void main(String args[]){ String s1=&apos;hello&apos;; String s2=&apos;&apos;; String s3=&apos;me&apos;; System.out.println(s1.compareTo(s2)); System.out.println(s2.compareTo(s3)); }} 
Testaa nyt

Lähtö:

 5 -2 

Java-merkkijono vertailuTo(): ​​isot ja pienet kirjaimet

Tarkistaaksemme, ottaako vertailuTo()-menetelmä huomioon merkkien isot ja pienet kirjaimet, teemme vertailun kahden merkkijonon välillä, jotka sisältävät samat kirjaimet samassa järjestyksessä.

Oletetaan, että merkkijono, jossa on kirjaimet isoina, ja toinen merkkijono, jossa kirjaimet ovat pieniä. Verrattaessa näitä kahta merkkijonoa, jos tulos on 0, vertaaTo()-metodi ei ota huomioon merkkien isot ja pienet kirjaimet; muussa tapauksessa menetelmä ottaa huomioon merkkien kirjainherkkyyden.

Tiedoston nimi: VertaaEsimerkki3.java

 public class CompareToExample3 { // main method public static void main(String argvs[]) { // input string in uppercase String st1 = new String(&apos;INDIA IS MY COUNTRY&apos;); // input string in lowercase String st2 = new String(&apos;india is my country&apos;); System.out.println(st1.compareTo(st2)); } } 

Lähtö:

 -32 

Johtopäätös: Tulosta tarkasteltaessa on selvää, että tulos ei ole nolla. Siksi vertaaTo()-menetelmä huolehtii merkkien isojen ja pienten kirjainten välisestä herkkyydestä.

Java-merkkijono vertailuTo(): ​​ClassCastException

The ClassCastException heitetään, kun keskenään yhteensopimattomia esineitä verrataan. Seuraavassa esimerkissä vertaamme ArrayList (al) -objektia merkkijonoliteraaliin ('Sehwag').

Tiedoston nimi: VertaaEsimerkki4.java

 // import statement import java.util.*; class Players { private String name; // constructor of the class public Players(String str) { name = str; } } public class CompareToExample4 { // main method public static void main(String[] args) { Players ronaldo = new Players(&apos;Ronaldo&apos;); Players sachin = new Players(&apos;Sachin&apos;); Players messi = new Players(&apos;Messi&apos;); ArrayList al = new ArrayList(); al.add(ronaldo); al.add(sachin); al.add(messi); // performing binary search on the list al Collections.binarySearch(al, &apos;Sehwag&apos;, null); } } 

Lähtö:

 Exception in thread &apos;main&apos; java.lang.ClassCastException: class Players cannot be cast to class java.lang.Comparable 

Java-merkkijono vertailuTo(): ​​NullPointerException

NullPointerException heitetään, kun nolla-objekti kutsuu vertailuTo()-menetelmän. Huomioi seuraava esimerkki.

voiko luokka laajentaa useita luokkia

Tiedoston nimi: VertaaEsimerkki5.java

 public class CompareToExample5 { // main method public static void main(String[] args) { String str = null; // null is invoking the compareTo method. Hence, the NullPointerException // will be raised int no = str.compareTo(&apos;India is my country.&apos;); System.out.println(no); } } 

Lähtö:

 Exception in thread &apos;main&apos; java.lang.NullPointerException at CompareToExample5.main(CompareToExample5.java:9)