我必须编写一个程序来创建一个数组,其中仅放入正数,但我不知道如何验证元素“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
最佳答案
常规数组没有方法 contains()
。您也不能使用 Arrays.asList
使用原始类型,因为 Java 的泛型不支持像 List<int>
这样的原始类型。您可以使用 Integer[] b
而不是int[] b
,那么你的例子就可以正常工作。
但是对于原始类型,您可以使用流 api,例如:
Arrays.stream(b).anyMatch(value -> value == a[j])
关于java - 如何检查 Java 中的某个项目是否在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070180/