Finding a number in an array

I wanted to ask what I am doing wrong because the if statement is false every time I run the program. I also tried using .equals(num)

instead Array.asList(num)

to check if the value exists, but that caused the for loop to repeat "Not in database" multiple times.

-2


source to share


1 answer


Arrays.asList(Data)

creates a list whose only element is an int array (i.e. List<int[]>

). Therefore it Arrays.asList(Data).contains(num))

always returns false.

Try changing your array to:

Integer Data[] = new Integer[n];

      



This will Arrays.asList(Data)

create a list Integer

( List<Integer>

) containing all the integers of the original array that you need.

The reason for this behavior is Arrays.asList

that one or more is waiting for Object

its input. If you pass an array from Object

(for example Integer[]

), it is equivalent to passing multiple Object

s. If, however, you pass in an array of primitives (for example int[]

), the only one Object

in your input is the array itself, so it Arrays.asList()

creates a list whose only element is that array.

+3


source







All Articles