Search code examples
javalistseleniumcontains

How to check if value is present in list in java


I want to match this Value 199.04 in TaxList. Below is my code

List<BigDecimal> TaxList = new ArrayList<BigDecimal>();   

String NetP=driver.findElement(getNetPension).getAttribute("value");
float NetPension = new Float(NetP);
log.info("Value of Net Pension on screen : "+ NetPension);

if(TaxList.contains(NetPension)) 
{   
     log.info("Income tax value from the database is matching with the value on the screen");
}
else 
{
     log.warn("Both the values are different.Net pension is:" +NetPension );
}

I am printing the TaxList in console

[199.04, 610.72, 122.12, 866.52, 94.56, 143.48, 78.28, 132.6, 12.9, 32.03, 1797.38, 128.14, 724.94]. even though value 199.04 is present.it goes to else part

Both the values are different.Net pension is:199.04


Solution

  • When calling the contains method on an ArrayList, it performs an equals() call on all contained elements. What could be happening here, is that instances of the class BigDecimal are not correctly compared to values of the float type.

    Consider stepping into the contains() and check what is done with the float value when being compared to BigDecimal. Another possible solution would be to convert the float value to a BigDecimal by yourself.