I’m looking for the Java equivalent of C#’s new[] { 0, 2, 3, 5, 6, 7, 8, 9 }.Contains(digit).
I know I can use something like this, but I’d rather use something more concise:
if (digit == 0 || digit == 2 || digit == 3 || digit == 5 || digit == 6 || digit == 7 || digit == 8 || digit == 9)
{
}
>Solution :
If you want to search in a List:
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
call contains() method but its complexity is O(n).
nums.contains(searchNumber);
If you want to search in a Set:
Set<Integer> nums = new HashSet<>();
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(4);
nums.contains(searchNumber);
here contains() runs in O(1) which is better than O(n).
Overall, it depends on how many elements your collection will store. If a collection is small, using a HashSet can be overhead.