[英]why cant we use <, <=, >,>= relational operators on String?
I want to know why we cant use the <
, <=
, >
or >=
relational operators on Strings.我想知道为什么我们不能在字符串上使用
<
、 <=
、 >
或>=
关系运算符。
import java.util.*;
public class Coffee{
public static void main(String args[]){
String s1="Cat";
String s2="Dog";
System.out.println(s1 < s2);
}
}
gives the error "operator < cannot be applied to java.lang.String".给出错误“运算符 < 不能应用于 java.lang.String”。
Why can't Java compare strings like this: C < D
?为什么 Java 不能像这样比较字符串:
C < D
?
The simple answer is: because they weren't implemented.简单的答案是:因为它们没有被实施。 Java (unlike eg C/C++) does not rely on operator overloading, so you have to get the value of a String with
length
method and then compare the results with your < > <= >=
operators. Java(不像C/C++)不依赖于操作符重载,所以你必须用
length
方法获取String的值,然后将结果与你的< > <= >=
操作符进行比较。
Side note: Strings in Java also implement Comparable interface.旁注:Java 中的字符串也实现了 Comparable 接口。 It allows you to use compareTo method, which returns 0 if the argument is a strings are equal, a value less than 0 if the argument is greater than string which you run this method on;
它允许您使用 compareTo 方法,如果参数是字符串相等则返回 0,如果参数大于运行此方法的字符串,则返回值小于 0; and a value greater than 0 if the argument is a string smaller than this string.
如果参数是小于此字符串的字符串,则值大于 0。
Side note 2: By "greater string" I mean lexicographically greater (alphabetically).旁注 2:“更大的字符串”是指在字典上更大(按字母顺序)。
String is not a primitive data type like int and double are. String 不是像 int 和 double 那样的原始数据类型。 Strings are objects.
字符串是对象。
For Strings, the relational operator, ==, only checks to see if the objects "point" to the same data in the heap.对于字符串,关系运算符 == 仅检查对象是否“指向”堆中的相同数据。
For example,例如,
String s1="Cat";
String s2= new String("Cat");
if(s1==s2)
System.out.println("They are the same");
The if statement WILL NOT execute. if 语句将不会执行。 This is because after you created an instance of "Cat", you create another instance of "Cat," in the heap.
这是因为在您创建了“Cat”实例之后,您在堆中创建了另一个“Cat”实例。 The two variables do not "point" to the same data.
这两个变量并不“指向”相同的数据。
compareTo methods check to see if the actual data that the variables are allocated to in a heap are equal to each other, and is one of the many correct ways to see if two String objects are equal to each other. compareTo 方法检查堆中分配给变量的实际数据是否彼此相等,并且是查看两个 String 对象是否彼此相等的许多正确方法之一。
I hope it helped, if my response is unclear, please do not hesitate to ask.希望对您有所帮助,如果我的回答不清楚,请随时提问。
If you really want to do this, use the compareTo
result.如果您真的想这样做,请使用
compareTo
结果。
if ("a".compareTo("b") >= 0) {
// do stuff
}
If you want to ignore case you can do:如果你想忽略大小写,你可以这样做:
if (String.CASE_INSENSITIVE_ORDER.compare("A", "b") <= 0) {
// do stuff
}
Here's the right way:这是正确的方法:
import java.util.*;
public class Coffee {
public static void main(String args[]) {
String s1="Cat";
String s2="Dog";
System.out.println(s1.compareTo(s2));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.