-1

I have table of int[]. I have for loop with every user and I do:

int[] ids = (values) 
for (User user : listAfterProcessing) {
    if (user.getId().equals(ids)) { ... } 
}

They didnt work, Although the user id is in this table... Thanks for help :)

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Kima321
  • 55
  • 1
  • 1
  • 8

2 Answers2

3

You are checking whether the result of getId() equals the entire array ids, which is by default a comparison to the array's hashcode.

According to an answer in this question: How to convert int[] into List<Integer> in Java?

there is no quick way to convert.

The solution with Arrays.asList(), which I suggested in the first version of my answer, doesn't work here, sorry.

B from C
  • 66
  • 4
  • When I try this: if (Arrays.asList(ids).contains(user.getId())) this didnt work :( – Kima321 Jan 13 '18 at 17:22
  • you can do `List tempList = Arrays.stream(ids) .boxed() .collect(Collectors.toList());` before the loop and then change the condition to `if (tempList.contains(user.getId()))` – Ousmane D. Jan 13 '18 at 17:31
  • or change the condition to `if(Arrays.stream(ids).anyMatch(id -> id == user.getId()))`, or do another loop inside the current one looping over the array of ids and then do your comparison. – Ousmane D. Jan 13 '18 at 17:32
0

Comparing an int array to a single Integer will not get you the result you want. You could go through the whole array and test every cell for the value, or you could keep the array sorted and do a binary search:

import java.util.Arrays;

Arrays.sort(ids);
if(Arrays.binarySearch(ids, user.getId().intValue()) >= 0) {}
O.O.Balance
  • 2,930
  • 5
  • 23
  • 35