![](/img/trans.png)
[英]Type mismatch: cannot convert from int to int[] error in Java code
[英]Java: Type mismatch: cannot convert from null to int
我想创建一个方法来检查两个数组是否相同(不使用任何导入)。 顺序无关紧要,它可以包含重复项,两个数组需要保持不变! 我的想法是复制第一个数组,然后将复制数组与第二个数组进行比较。 如果我找到一个有效的对,从复制数组中删除该项目,以便它可以处理重复。 但由于类型不匹配,我无法删除任何项目。 我的代码:
解决方案.java
public class Solution {
public static boolean areTheyTheSame(int[] a, int[] b)
{
if (a.length == b.length)
{
//fill the temp array with the elements of a
int temp[] = new int[a.length];
for (int i = 0 ; i < a.length ; i++)
{
temp[i] = a[i];
}
//check if the temp array and the b array are the same
for (int i = 0 ; i < a.length ; i++)
{
for (int j = 0 ; j < a.length ; j++)
{
if (temp[i] == b[j])
{
temp[i] = null; // Type mismatch: cannot convert from null to int
}
else
{
return false;
}
}
}
return true;
}
return false;
}
}
测试.java
public class Test {
public static void main(String[] args) {
int[] a = new int[]{121, 144, 19, 161, 19, 144, 19, 11};
int[] b = new int[]{121, 19, 19, 144, 161, 144, 11, 19};
if (Solution.areTheyTheSame(a, b) == true)
{
System.out.println("Equal");
}
else
{
System.out.println("Not equal");
}
}
}
这里有几个问题:
如果你想那样做,请使用“Integer temp[];” (您可以将其余部分保留为 int)。 Java 会自动在 int 和 Integer 之间进行转换,因此您不必担心那里的类型转换。 其他原语(不能为“null”)是 boolean、long、double 和 float。
设置数组后,您不会检查所有内容是否为空。 添加额外的检查后,它应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.