gpt4 book ai didi

c# - 从 C# 转换后 Java 代码中的错误

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:17 24 4
gpt4 key购买 nike

这是一个打印数组中重复 int 的函数。在 C# 中:

int [] ReturnDups(int[] a)
{
int repeats = 0;
Dictionary<int, bool> hash = new Dictionary<int>();
for(int i = 0; i < a.Length i++)
{
bool repeatSeen;
if (hash.TryGetValue(a[i], out repeatSeen))
{
if (!repeatSeen)
{
hash[a[i]] = true;
repeats ++;
}
}
else
{
hash[a[i]] = false;
}
}

int[] result = new int[repeats];
int current = 0;
if (repeats > 0)
{
foreach(KeyValuePair<int,bool> p in hash)
{
if(p.Value)
{
result[current++] = p.Key;
}
}
}
return result;
}

现已通过Tangible软件的工具转换为JAVA。在java中:

private int[] ReturnDups(int[] a)
{
int repeats = 0;
java.util.HashMap<Integer, Boolean> hash = new java.util.HashMap<Integer>();
for (int i = 0; i < a.length i++)
{
boolean repeatSeen = false;
if (hash.containsKey(a[i]) ? (repeatSeen = hash.get(a[i])) == repeatSeen : false)
{
if (!repeatSeen)
{
hash.put(a[i], true);
repeats++;
}
}
else
{
hash.put(a[i], false);
}
}

int[] result = new int[repeats];
int current = 0;
if (repeats > 0)
{
for (java.util.Map.Entry<Integer,Boolean> p : hash.entrySet())
{
if (p.getValue())
{
result[current++] = p.getKey();
}
}
}

return result;
}

但是findbug发现这行代码是bug。我也觉得很奇怪。

if (hash.containsKey(a[i]) ? (repeatSeen = hash.get(a[i])) == repeatSeen : false)

有人可以向我解释一下这一行的作用以及如何正确地用 java 编写它吗?谢谢

最佳答案

您的 TryGetValue 代码过于复杂 - 这个简单的翻译应该可以工作:

if ( hash.containsKey(a[i]) ) {
if (!hash.get(a[i])) {
hash.put(a[i], true);
}
} else {
hash.put(a[i], false);
}

C# 有一种方法来获取该值,并有一个标志告诉您是否在一次调用中找到了该值; Java 没有类似的 API,因为它缺乏通过引用传递变量的能力。

关于c# - 从 C# 转换后 Java 代码中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20895764/

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