I have list List myList, that contains Long values which is returned from a database operation. I am checking if the list contains a specific Long value. I am trying to do myList.contains(value), but unfortunately it returns false even though the List contains the specific value! Why it is happening? How to resolve it?
Repository class
@Repository
public interface CarsRepository extends JpaRepository<Cars, Long> {
@Query(value = "select id from Cars WHERE colour = ?1", nativeQuery=true)
public List<Long> fetchCarsWithColour(String colour);
}
Calling method
Long specificCarId = 3456L;
List<Long> carIds = carsRepository.fetchCarsWithColour("red");
System.out.println(carIds); // [3456, 3457]
System.out.println(specificCarId); // 3456
if(carIds.contains(specificCarId)){
System.out.println("Inside if");
return true;
} else {
System.out.println("Inside else");
return false;
}
Console
[3456, 3457]
3456
Inside else
The calling method returns false even though it has the value 3456L.
UPDATE
I have tried printing List carIds as below. It throws exception java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
for(Long value : carIds){
System.out.println(value);
}
So somehow, the repository call returns List instead of List but because of autoboxing, it perfectly fits into List