比较两字符串内容是否相同: String a="abcdef"; String b="abcdef"; if(a.equals(b)){ System.out.println("The two string is same!"); } else{ System.out.println("The two string is different!"); }
TMD,faint,来晚了,公司的网络真TMD废,答问题都赶不上
to: javabandit(bandit) 代码是jdk1.4.1_02的源代码.还没有必要到自己写String.equals()的地步. :)
string的比较用equals或者compareTo
string的比较用equals或者compareTo
非初始数据类型(int double char byte long float)都可以用equals() AND compareTo()两个函数,String 也不例外
to jing929(贝贝): 你的回答太不严谨了. (1) 非初始数据类型,意思明白,说法觉得别扭. (2) 不是所有的类都可以使用equals比较的,比如: public class Foo { public boolean equals(Object o) {throw new UnsupportedOperationException();} public int hashCode() {throw new UnsupportedOperationException();} } 你怎么比较两个Foo的实例? (3) compareTo方法在什么地方定义的?不是每个类都需要实现Comparable接口的.
以下是String's equals的源代码:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
String str = "hello";
if(str.equals("hello"))
{
...
}
或者
if(str.compareTo("hello") == 0)
{
....
}
String a="abcdef";
String b="abcdef";
if(a.equals(b)){
System.out.println("The two string is same!");
}
else{
System.out.println("The two string is different!");
}
代码是jdk1.4.1_02的源代码.还没有必要到自己写String.equals()的地步. :)
你的回答太不严谨了.
(1) 非初始数据类型,意思明白,说法觉得别扭.
(2) 不是所有的类都可以使用equals比较的,比如:
public class Foo {
public boolean equals(Object o) {throw new UnsupportedOperationException();}
public int hashCode() {throw new UnsupportedOperationException();}
}
你怎么比较两个Foo的实例?
(3) compareTo方法在什么地方定义的?不是每个类都需要实现Comparable接口的.