Java:类型不匹配:无法从null转换为int 您正在数组中使用“原始” int。这不是对象,因此不能将其设置为“ null”。您没有比较最终的临时数组

我想创建一个方法,该方法可以检查两个数组是否相同(不使用任何导入)。顺序无关紧要,它可以包含重复项,并且两个数组必须保持相同!我的想法是复制第一个数组,然后将复制的数组与第二个数组进行比较。如果我找到有效的一对,请从复制数组中删除该项目,以便它可以处理重复项。但是由于类型不匹配,我无法删除任何项目。我的代码:

Solution.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;
    }
}

Test.java

public class Test {

    public static void main(String[] args) {

        int[] a = new int[]{121,144,19,161,11};
        int[] b = new int[]{121,11,19};

        if (Solution.areTheyTheSame(a,b) == true)
        {
            System.out.println("Equal");
        }
        else 
        {
            System.out.println("Not equal");
        }

    }

}
zhourqdl 回答:Java:类型不匹配:无法从null转换为int 您正在数组中使用“原始” int。这不是对象,因此不能将其设置为“ null”。您没有比较最终的临时数组

那里有一些问题:

您正在数组中使用“原始” int。这不是对象,因此不能将其设置为“ null”。

如果要那样做,请使用“ Integer temp [];”。 (您可以将其余的保留为int)。 Java将自动在int和Integer之间转换,因此您不必担心那里的类型转换。其他基元(不能为“ null”)是布尔型,长型,双精度和浮点型。

您没有比较最终的临时数组

设置数组后,无需检查所有内容是否为空。添加了额外的检查后,它应该可以正常工作。

本文链接:https://www.f2er.com/2681553.html

大家都在问