[英]How do I check if an item is in an array in Java?
我必須執行一個程序,該程序創建一個數組,其中僅放置正數,但是我不知道如何驗證元素“ 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
與原始Arrays.asList
一起使用,因為Java的泛型不支持諸如List<int>
類的原始類型。 您可以使用Integer[] b
而不是int[] b
,然后您的示例可以正常工作。
但是使用原始類型,您可以使用流api,例如:
Arrays.stream(b).anyMatch(value -> value == a[j])
修改代碼為:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.