I was wondering if it is possible to compare strings as if they were numbers. For instance is there any way you could make it so that "Cat" > "Dog"

- 14,843
- 23
- 75
- 96

- 9,106
- 30
- 75
- 101
-
1How is "Cat" or "Dog" a number? Why would "Cat" > "Dog" by the logic of numbers? – Karl Knechtel Dec 05 '10 at 00:46
-
Can you elaborate on your scenario? Do you just want to be able to compare strings? or do you want to assign special values to specific words and have one be 'greater' than another? – akf Dec 05 '10 at 00:53
-
I would like to do the latter. – Steffan Harris Dec 05 '10 at 00:56
7 Answers
You can't use operators (e.g. "Cat" < "Dog"
) as you suggest. As @larsmans says that would require operator overloading which Java doesn't provide. However, you can still compare strings using "Cat".compareTo("Dog")
which returns 0 if the strings are equal, a number greater than 0 if "Cat"
is lexicographically less than "Dog"
, or a negative number otherwise.
See this page

- 134,091
- 45
- 190
- 216
Just implement the Comparator interface and implement the comparison any way you like.

- 14,843
- 23
- 75
- 96
You can't. This would require operator overloading, which Java won't let you.
-
Ummm, + operator? It does, you just cannot define your own versions. – David Watson Dec 05 '10 at 01:33
Nope, doesn't exist. You have to use compareTo().

- 1,663
- 2
- 18
- 29
-
2String.compareTo already exists, so we should instead implement the `Comparator` interface. – Karl Knechtel Dec 05 '10 at 00:47
You need to use some method as below :
int compare(String s1, String s2); // write code to do comparison.

- 39,895
- 28
- 133
- 186
Since the only way to do this is to keep a set value for each word, you'd be using arrays, or some other form of data storage.
Here is an example where you just keep the words, and their corresponding values in two arrays (note, they must be in the same order, so the first word corresponds with the first number, etc).
public static String[] words = {"cat","dog","banana"};
public static int[] value = {3,4,5};
public static void main(String[] args){
if(valOf("Cat") > valOf("Dog")){
System.out.print("Cat is greater than Dog");
}
else{
System.out.print("Cat is not greater than Dog");
}
}
public static int valOf(String str){
for(int x=0;x<words.length;x++){
if(str.equalsIgnoreCase(words[x])){
return value[x];
}
}
return -1;
}

- 3,635
- 2
- 28
- 34