A simple Java code for checking whether an element exists in an array or not:
import java.util.Arrays;
public class Main {
static int[] numbers = {813, 907, 908, 909, 910};
public static void main(String[] args) {
int number = 907;
//Integer number = 907; // the same thing -- it's not found.
boolean b = Arrays.asList(numbers).contains(number);
System.out.println(b); // => false
}
}
1) Why doesn't it find 907 in the array?
2) If there is a better way of doing it, go ahead and share your knowledge.
UPDATE:
It was said that asList
converts your int[]
into a List<int[]>
with a single member: the original list. However, I expect the following code to give me 1, but it gives me 5:
System.out.println(Arrays.asList(numbers).size());
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
The isArray() method of Class is used to check whether an object is an array or not. The method returns true if the given object is an array. Otherwise, it returns false .
To check if an array contains only numbers:Use the Array. every() method to iterate over the array. On each iteration, check if the type of the current element is number . The every method will return true if the array contains only numbers and false otherwise.
The problem is that Arrays.asList(numbers)
isn't doing what you think. It is converting your int[]
into a List<int[]>
with a single member: the original list.
You can do a simple linear search or, if your numbers
array is always sorted, use Arrays.binarySearch(numbers, 907);
and test whether the result is negative (meaning not found).
Lists don't contain primitives, so Arrays.asList(int[]) will produce a List
with one entry of type int[]
.
This code works:
static Integer[] numbers = {813, 907, 908, 909, 910};
public static void main(String[] args) {
Integer number = 907;
boolean b = Arrays.asList(numbers).contains(number);
System.out.println(b); // => false
}
For your question as what will Arrays.asList(numbers)
contain as long as it is an int[]
:
This code:
static int[] numbers = {813, 907, 908, 909, 910};
public static void main(String[] args) {
int number = 907;
List<int[]> list = Arrays.asList(numbers);
boolean b = list.contains(number);
System.out.println(b); // => false
System.out.println("list: " + list);
for(int[] next : list) {
System.out.println("content: " + Arrays.toString(next));
}
}
has this result:
false
list: [[I@da89a7]
content: [813, 907, 908, 909, 910]
As you can see, the list
contains one element of type int[]
(the [[I
indicate the int[]
). It has the elements that were initially created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With