2 回答

TA贡献1871条经验 获得超13个赞
1) 字符串文字将存储在字符串常量池中。这里的值不能重复。例如,如果您尝试创建两个具有相同值的变量,则第二个变量值不能存储在 SCP 中,而是会获得第一个值地址。
2) 但是使用new String会创建两个对象,即使两个对象具有相同的值。
例子:
public class TestFile {
public static void main(String[] args) {
String name1 = "AAA";
String name2 = name1.intern();
String name3 = new String("AAA");
String name4 = name3.intern();
System.out.println(name1 == name2); // true
System.out.println(name2 == name4); // true
System.out.println(name3 == name4); // false
System.out.println(name3.equals(name4));
}
}
1) 这里 name1 和 name2 都是文字。所以比较为真。
2) name3 是对象,但我们使用的是 intern(),因此将获取将作为文字存储在 name4 中的对象的值。所以比较将是真实的。
3) 但是 name3 和 name4 comaprsion 将是 False。因为 name3 是对象而 name4 是文字。但如果您使用的是 .equals(),这将是正确的。

TA贡献1858条经验 获得超8个赞
String 的正确用法是:
Charset charset = StandardCharsets.ISO_8859_1;
...
current_user_eid = new String(msg, offset, length, charset);
}
else
return;
length = msg[off+1]*256 + msg[off];
offset = msg[off+3]*256 + msg[off+2];
current_user_eid = new String(msg, offset, length, charset);
length = msg[off+9]*256 + msg[off+8];
offset = msg[off+11]*256 + msg[off+10];
current_user_eid = new String(msg, offset, length, charset);
//current system user name "yaseer"
// String Comparison starts here....
String hard_str = "yaseer"; //
String eid_str = current_user_eid; //passing the fetched username which is yaseer
String eid_str_in = eid_str.intern(); // system username
String comp_str = "yaseer"; // String for comparison
System.out.println(hard_str_in == comp_str); // give true
System.out.println(eid_str_in == comp_str); // gives false
System.out.println(eid_str_in.equals(comp_str));
// gave true ("on screen"), expected to give false
如果我理解正确,最后两行会给出不同的结果。
对于纯 ASCII“yaseer”(假设您不使用带有错误 java 源代码/java 编译器编码的 EBCDIC 的 AS/400 工作,情况不应该如此)。
但是我看到current_user_eid被分配了两次,第一次分配了 6 个字节,这可以对应于带有 6 个字母的“yaseer”。
所以我认为第二个current_user_eid是混淆。
为它的值转储一个字符串:
System.out.println(Arrays.toString(eid_str_in.toCharArray()));
剩下的:.intern()不再是使用wrt效率的东西;因此也不是==。在早期版本中,内部常量进入有限大小的“永久内存生成”,如果过多且过于频繁地被实习,这有其缺点。
字节总是被转换为UnicodeString的charS(UTF-16),可能使用平台默认字符集。所以最好明确提供Charset,即使Charset.defaultCharset()明确说明平台依赖性。
添加回答
举报