equals
String类中方法的代码是
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;
}
Run Code Online (Sandbox Code Playgroud)
我有一个问题 - 为什么这个方法不使用hashCode()?
据我所知,hashCode()可以快速比较两个字符串.
更新:我知道,两个不相等的字符串,可以有相同的哈希值.但两个相等的字符串具有相等的哈希值.因此,通过使用hashCode(),我们可以立即看到两个字符串是不相等的.
我只是想,使用hashCode()方法可以很好的过滤器在equals
.
更新2:这里有一些代码,我们在这里谈论.
这是String方法等于的示例 …
我试图创建一个更快版本的String.equals()方法,并通过简单地复制它开始.我发现的结果非常令人困惑.当我运行复制粘贴版本,定时并将其与JVM版本进行比较时,JVM版本更快.差异从6倍到34倍不等!简单地说,字符串越长,差异就越大.
boolean equals(final char a[], final char b[]) {
int n = a.length;
int i = 0;
while (n-- != 0) {
if (a[i] != b[i]) return false;
i++;
}
return true;
}
public static void main() throws Exception {
String a = "blah balh balh";
String b = "blah balh balb";
long me = 0, jvm = 0;
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
final char lhs[] = (char[]) value.get(a);
final char rhs[] = (char[]) value.get(b);
for (int …
Run Code Online (Sandbox Code Playgroud) 我需要比较2 Strings
.我有以下方法可以想到:
equalsIgnoreCase
- 听说这是最快的,但我无法使用它,因为我的String区分大小写matches
- 可能是最慢的一个equals
compareTo
所以在上面的选项中,我留下了equals
和compareTo
.其中哪一个更快?
注意:字符串的输入数量很大[每秒5000左右].
我有一个字符串列表,我浏览它并计算"x"字符串的数量如下,但计数不打印我预期的值:
ArrayList<Integer> list = new ArrayList<Integer>();
List<String> strings = table.getValue(); //this gives ["y","z","d","x","x","d"]
int count = 0;
for (int i = 0; i < strings.size(); i++) {
if ((strings.get(i) == "x")) {
count++;
list.add(count);
}
}
System.out.println(list);
Run Code Online (Sandbox Code Playgroud)
这给[]
它应该是2因为我有2次出现"x"