gpt4 book ai didi

java - 为什么 String + '\u0000' 与 String 不同?

转载 作者:行者123 更新时间:2023-11-29 06:58:24 24 4
gpt4 key购买 nike

我的算法构造一个词并在 TST 中查找与该词关联的值。

private Node get(Node x, String key, int index) {
if (key.isEmpty()) {
return root;
}
if (x == null) {
return null;
}
char c = key.charAt(index);
if (c < x.val) {
return get(x.left, key, index);
} else if (c > x.val) {
return get(x.right, key, index);
} else if (index < key.length() - 1) {
return get(x.mid, key, index + 1);
} else {
return x;
}
}

每个节点都是这样构造的:

private class Node {
private char val;
private Node left, mid, right;
private Double selfWeight;
private double maxWeight;

/**
* Node constructor.
*/
private Node(char c) {
val = c;
maxWeight = 0.0;
selfWeight = null;
}
}

单词的最大权重在构造时设置,这是 TST 标准构造的修改版本:

private Node put(Node x, String key, Double weight, int index) {
char c = key.charAt(index);
if (x == null) {
x = new Node();
x.val = c;
}
if (c < x.val) {
x.left = put(x.left, key, weight, index);
} else if (c > x.val) {
x.right = put(x.right, key, weight, index);
} else if (index < key.length() - 1) {
x.mid = put(x.mid, key, weight, index + 1);
} else {
x.selfWeight = weight;
}
if (weight > x.maxWeight) {
x.maxWeight = weight;
}
return x;
}

运行我的算法时,如果我插入,例如权重为 20 的“hello”,我在 get("hello"+ '\u0000'); 上搜索该方法将返回 null,就像我调用 get("hello") 该方法将返回 20。这是为什么?

我的逻辑是添加 'null' 字符不会更改字符串,打印出 "hello"+ '\u0000' 证实了这一点。发生了什么事?

最佳答案

它们不是同一个字符串,因为它们不包含相同的字符。您看不到某个字符并不意味着它不存在。

如果你转换了hello到 unicode 那么你所声称的是

0068 0065 006C 006C 006F 00000068 0065 006C 006C 006F相同

如果您需要进一步解释,请检查 String 的 equals 方法

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.equals%28java.lang.Object%29

/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(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;
}

关于java - 为什么 String + '\u0000' 与 String 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29997529/

24 4 0