gpt4 book ai didi

java - 为什么在 Java 中使用 HashMap 会失败?

转载 作者:行者123 更新时间:2023-12-01 19:29:17 26 4
gpt4 key购买 nike

import java.util.HashMap;

public class Main {
public static void main(String[] args) {

//Use inputs from https://pastebin.com/DMQ6xqKe and assign to s * t, as stackoverflow limited character use
String s = "";
String t = "";

System.out.println(isAnagram(s, t));
}

public static boolean isAnagram(String s, String t) {
HashMap<Character, Integer> sMap = new HashMap<>();
HashMap<Character, Integer> tMap = new HashMap<>();

if(s.length() != t.length())
{
return false;
}

for(int i = 0; i < s.length(); i++)
{
if(sMap.containsKey(s.charAt(i)))
{
sMap.replace(s.charAt(i), sMap.get(s.charAt(i)) + 1);
}
else
{
sMap.put(s.charAt(i), 1);
}
}

for(int i = 0; i < t.length(); i++)
{
if(tMap.containsKey(t.charAt(i)))
{
tMap.replace(t.charAt(i), tMap.get(t.charAt(i)) + 1);
}
else
{
tMap.put(t.charAt(i), 1);
}
}

//FAILS BUT WHY!?!??!?
for(int i = 0; i < s.length(); i++)
{
System.out.println("outside " + sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
if(sMap.get(s.charAt(i)) != tMap.get(s.charAt(i)))
{
System.out.println(sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
return false;
}
}

//PASSES BUT PREVIOUS FAILS?!!?!??!
// if(!sMap.equals(tMap))
// {
// return false;
// }

return true;
}
}

此代码失败,但使用 .equals 的注释代码有效。我实在不明白。记录了这些值,它们匹配,但检查失败,显示不同的值。

最佳答案

== 运算符比较两个对象引用。 Object 类型的 equals 方法执行相同的操作,但某些类使用新功能重写该方法。例如,如果“x”==“x”是不同的对象,则它们可能会失败。 "x".equals("x") 为 true。

String x = "@";
String y = x;
x == y; // true, its the same reference.

希望这有帮助吗?

关于java - 为什么在 Java 中使用 HashMap 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60289019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com