1

Attempting to write an insertion sort to sort an array of strings..

public static void insertionSort(String[] list) 
{
    for (int i = 1; i <list.length; i++)
    {
        String currentElement = list[i];
        int k;
        for (k=i-1; k >= 0 && list[k] > currentElement; k--) //error here
        {
            list[k+1]=list[k];
        }
        list[k+1] = currentElement;
    }
}

I'm getting the error The operator > is undefined for the argument type, but I thought I had learned in class that you could compare strings with >, <, etc? How would I go about fixing this problem?

1
  • Maybe you had learned that in a VB programming class, but definitely not Java (or most other languages for that matter). Commented Mar 13, 2014 at 20:18

2 Answers 2

4

You cannot compare objects, including Strings, with comparison operators such as >. You must call a method that does the comparison. String is Comparable<String>, so replace

list[k] > currentElement

with

list[k].compareTo(currentElement) > 0
Sign up to request clarification or add additional context in comments.

Comments

0

No. You cannot compare any Object including String with the greater or smaller operators.

You can compare strings using a collation, which is language-specific. If you want to compare strings based on the Unicode values of their characters, you can use the compareTo(String) method of the String class. See the Java documentation for the String class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.