![](/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.