相关疑难解决方法(0)

为什么String中的equals方法不使用哈希?

equalsString类中方法的代码是

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方法等于的示例 …

java string hashcode

44
推荐指数
3
解决办法
4633
查看次数

JVM何时使用内在函数

为什么在JVM内部类中存在的某些代码模式被转换为内部函数,而从我自己的类调用时相同的模式则不然.

例:

bitCount函数,当从Integer.bitCount(i)内调用时,将变成一个内在函数.但是当复制到我的类中然后调用将需要更长的时间来执行.

相比

Integer.bitCount(i) 
MyClass.bitCount(i) 


public static int bitCount(int i) {
    // HD, Figure 5-2
    i = i - ((i >>> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    i = (i + (i >>> 4)) & 0x0f0f0f0f;
    i = i + (i >>> 8);
    i = i + (i >>> 16);
    return i & 0x3f;
}
Run Code Online (Sandbox Code Playgroud)

java performance jvm intrinsics

21
推荐指数
2
解决办法
6121
查看次数

String.equals()如何工作

我一直试图了解一些API方法的工作原理

下面是java.lang.String类的equals方法的片段

有人可以告诉我代码实际上是如何比较两个字符串的.我得到了计数的重要性,但偏移意味着什么.这些变量如何获得价值?

就像我创建一个String.这些是如何初始化的.

详细的逐行描述以及实例变量,值,计数,偏移等的初始化方式和时间?

 public boolean equals(Object anObject) {
  1014           if (this == anObject) {
  1015               return true;
  1016           }
  1017           if (anObject instanceof String) {
  1018               String anotherString = (String)anObject;
  1019               int n = count;
  1020               if (n == anotherString.count) {
  1021                   char v1[] = value;
  1022                   char v2[] = anotherString.value;
  1023                   int i = offset;
  1024                   int j = anotherString.offset;
  1025                   while (n-- != 0) {
  1026                       if (v1[i++] != v2[j++])
  1027                           return false;
  1028                   }
  1029 …
Run Code Online (Sandbox Code Playgroud)

java string equals

2
推荐指数
1
解决办法
2398
查看次数

标签 统计

java ×3

string ×2

equals ×1

hashcode ×1

intrinsics ×1

jvm ×1

performance ×1