Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: compareTo() question

  1. #1
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default compareTo() question

    Hi guys, so i was following some examples with generic methods that return a value and i made this:

    public class Main {
        public static void main(String[] args){
     
            System.out.println(max(23,42,1));
     
            System.out.println();
     
            System.out.println(max("alexa","mauricio","scarlet"));
     
        }
     
     
        public static <T extends Comparable<T>> T  max(T a, T b, T c){
            T maximum = a;
     
            if(b.compareTo(a)>0)
                maximum = b;
     
            if (c.compareTo(maximum)>0)
                maximum = c;
     
            return maximum;
        }
    }

    if you compile it, when it compares the strings variables why does it return "scarlet" as greater than the other 2? i seriously don't get it, i tried to look for the compareTo() method but all it mentions is the usage and that it returns a negative number if the variable you are comparing with another is lesser than the other, 0 if they are equal and a possive number if it is greater. But why? can someone please explain how does it compare it? i thought it was because of the length.


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: compareTo() question

    The letters are represented by numbers in the background. Run this:
    public class PrintCharValue {
    	public static void main(String[] args) {
    		System.out.println((int)'a');
    		System.out.println((int)'m');
    		System.out.println((int)'s');
    		System.out.println('a' < 'm');
    		System.out.println('m' < 's');
    	}
    }}

  3. #3
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: compareTo() question

    oooohhh i see! so then when it compares the strings it adds up every value from every character and the total is what is being compared i assume (?)

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: compareTo() question

        /**
         * Compares two strings lexicographically.
         * The comparison is based on the Unicode value of each character in
         * the strings. The character sequence represented by this
         * <code>String</code> object is compared lexicographically to the
         * character sequence represented by the argument string. The result is
         * a negative integer if this <code>String</code> object
         * lexicographically precedes the argument string. The result is a
         * positive integer if this <code>String</code> object lexicographically
         * follows the argument string. The result is zero if the strings
         * are equal; <code>compareTo</code> returns <code>0</code> exactly when
         * the {@link #equals(Object)} method would return <code>true</code>.
         * <p>
         * 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 <i>k</i> be the smallest such index; then the string
         * whose character at position <i>k</i> has the smaller value, as
         * determined by using the &lt; operator, lexicographically precedes the
         * other string. In this case, <code>compareTo</code> returns the
         * difference of the two character values at position <code>k</code> in
         * the two string -- that is, the value:
         * <blockquote><pre>
         * this.charAt(k)-anotherString.charAt(k)
         * </pre></blockquote>
         * If there is no index position at which they differ, then the shorter
         * string lexicographically precedes the longer string. In this case,
         * <code>compareTo</code> returns the difference of the lengths of the
         * strings -- that is, the value:
         * <blockquote><pre>
         * this.length()-anotherString.length()
         * </pre></blockquote>
         *
         * @param   anotherString   the <code>String</code> to be compared.
         * @return  the value <code>0</code> if the argument string is equal to
         *          this string; a value less than <code>0</code> if this string
         *          is lexicographically less than the string argument; and a
         *          value greater than <code>0</code> if this string is
         *          lexicographically greater than the string argument.
         */
        public int compareTo(String anotherString) {
            int len1 = value.length;
            int len2 = anotherString.value.length;
            int lim = Math.min(len1, len2);
            char v1[] = value;
            char v2[] = anotherString.value;
     
            int k = 0;
            while (k < lim) {
                char c1 = v1[k];
                char c2 = v2[k];
                if (c1 != c2) {
                    return c1 - c2;
                }
                k++;
            }
            return len1 - len2;
        }

  5. The Following User Says Thank You to jps For This Useful Post:

    Hikaros (September 9th, 2013)

  6. #5

  7. The Following User Says Thank You to helloworld922 For This Useful Post:

    Hikaros (September 9th, 2013)

  8. #6
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: compareTo() question

    Ooohh i see! thanks! i don't think i fully understand it but from here it should be better if i do some testing myself o: Thank you :3

Similar Threads

  1. What does compareTo method of String do ?
    By djl1990 in forum Java Theory & Questions
    Replies: 5
    Last Post: December 18th, 2012, 03:39 AM
  2. Problem with string.compareTo();
    By Drasumok in forum What's Wrong With My Code?
    Replies: 6
    Last Post: November 30th, 2012, 04:31 PM
  3. [SOLVED] comparing objects using compareTo
    By jslice3 in forum Object Oriented Programming
    Replies: 3
    Last Post: November 19th, 2012, 10:09 PM
  4. Implementing the compareTo method?
    By colerelm in forum Java Theory & Questions
    Replies: 2
    Last Post: December 3rd, 2011, 07:47 PM
  5. Help Me with my Program CompareTo!!!!
    By WantHelp in forum What's Wrong With My Code?
    Replies: 14
    Last Post: July 7th, 2011, 12:54 PM