我一直在尝试了解一些 API 方法的工作原理
下面是java.lang.String类的equals方法片段
有人能告诉我代码是如何比较两个字符串的吗? 我明白计数的意义,但偏移意味着什么。这些变量如何获得值?
就像我创建一个字符串一样。这些是如何初始化的。
详细的逐行描述以及实例变量、值、计数、偏移量等初始化的方式和时间??
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 return true;
1030 }
1031 }
1032 return false;
1033 }
最佳答案
逻辑上
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
与
相同for (int i = 0; i < n; i++) {
if (v1[i] != v2[j])
return false;
}
}
我不确定为什么 JVM 设计者会这样做。也许使用 while 循环比使用 for 循环可以提高性能。它在我看来很像 C,所以也许写这篇文章的人有 c 的背景。
Offset
用于定位字符串在 char 数组中的起始位置。内部字符串存储为 char 数组。这是值
if (v1[i++] != v2[j++])
return false;
检查字符串底层 char 数组中的字符。
一行一行
如果引用指向同一个对象,则必须等号
1014 if (this == anObject) {
1015 return true;
1016 }
如果对象是字符串,则检查它们是否相等
1017 if (anObject instanceof String) {
将传入的参数转换为字符串。
1018 String anotherString = (String)anObject;
记住this.string的长度
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;
遍历 char 数组。如果值不同则返回false
1025 while (n-- != 0) {
1026 if (v1[i++] != v2[j++])
1027 return false;
1028 }
其他的都必须是真的
1029 return true;
1030 }
1031 }
如果不是String类型,则它们不能相等
1032 return false;
1033 }
要了解偏移量和值,请查看 String 类
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
构造函数初始化这些变量。默认构造函数代码如下。对于其他构造函数,您应该会看到类似的内容。
/**
* Initializes a newly created {@code String} object so that it represents
* an empty character sequence. Note that use of this constructor is
* unnecessary since Strings are immutable.
*/
public String() {
this.offset = 0;
this.count = 0;
this.value = new char[0];
}
This是一个很好的链接查看
关于java - String.equals() 是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12661335/