如何检查项目是否在Java数组中?

时间:2019-03-08 19:57:33

标签: java arrays methods

我必须执行一个程序,该程序创建一个数组,其中仅放置正数,但是我不知道如何验证元素“ a [j]”是否不在数组“ b”中。我在寻找方法(例如“包含”),但是程序给了我错误。

public class YourClassNameHere {
    public static int[] main(String[] args) {
        int[] a = {1,-2,3,-5};
        int[] b = new int[a.length];
        for(int i = 0; i < b.length; i++)
           for(int j = 0; j < a.length; j++)
            if(a[j] > 0)
            if(!(Arrays.asList(b).contains(a[j]))) // ?
                b[i] = a[j];
        return b;
    }
}

第8行:

 Error: cannot find symbol
      symbol:   variable Arrays
      location: class YourClassNameHere

2 个答案:

答案 0 :(得分:0)

常规数组没有方法contains()。同样,您不能将Arrays.asList与原始类型一起使用,因为Java的泛型不支持List<int>之类的原始类型。您可以使用Integer[] b代替int[] b,然后您的示例可以正常工作。

但是对于原始类型,您可以像这样使用流api:

Arrays.stream(b).anyMatch(value -> value == a[j])

答案 1 :(得分:0)

修改您的代码:

public class Main {

    public static void main(String[] args) {
        int[] a = { 1, -2, 3, -5 };
        //to store all positive values
        List<Integer> list = Arrays.stream(a).filter(number -> (number > 0)).boxed().collect(Collectors.toList());
        List<Integer> newList = new ArrayList<Integer>();
        //to remove duplicate values  
        for (Integer element : list) {
            if (!newList.contains(element)) {
                newList.add(element);
            }
        }
        // convert to array
        int[] newArr = new int[newList.size()];
        for (int i = 0; i < newList.size(); i++)
            newArr[i] = newList.get(i);

        for (int x : newArr)
            System.out.print(x + " ");

    }

}

输出:

1 3