I have list List<Long> list
, that contains: [160774, 7212775] and Long id = 7212775
. I need to check if the list contains an element with value of id
. How to do that? Unfortunately list.contains(id)
returns false
in my case.
I'm using it that way:
@RequestMapping("/case/{id}")
public String openCase(@PathVariable("id") Long id) {
log.debug(caseDAO.findAllCasesId()); // [160774, 7212775]
log.debug(id); // 7212775
if(caseDAO.findAllCasesId().contains(id)) {
return "case";
} else {
return "404";
}
}
Piece of DAO (Hibernate, but native sql here):
public List<Long> findAllCasesId() {
String sql = "select id from cases";
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
}
SOLVED
The problem was with caseDAO.findAllCasesId()
, that return list of Object
, not list of Long
. I corrected this by:
SQLQuery query = getSession().createSQLQuery(sql).addScalar("id", Hibernate.LONG);
Big thanks to: Nayuki Minase
ArrayList. contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.
contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it.
When autoboxing, you need to make sure you postfix the literal with an L i.e. Long id = 7212775L
for this to work.
Running the code below on eclipse helios:
public static void main(String[] args) {
List<Long> list = new ArrayList<Long>();
list.add(160774L);
list.add(7212775L);
System.out.println(list.contains(7212775L);
}
Output:
true
What you're doing wrong is
System.out.println(list.contains(7212775));
The problem is that your list takes Long objects and you are searching for a literal.
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