方法中的 BigDecimal 比较问题

BigDecimal comparison issue in method

我正在尝试根据高低价格范围过滤产品。这是我用

测试的 URL

http://localhost:8080/webstore/products/test?high=900&low=100

这是我的存储库(ProductRepository)

public interface ProductRepository {
    List<Product> getProductsByPriceFilter(BigDecimal high, BigDecimal low);
}

这是我的 InMemoryProductRepository class,它有原始数据和这个方法

public List<Product> getProductsByPriceFilter(BigDecimal high, BigDecimal low){
        List<Product> productsByPriceFilter = new ArrayList<Product>();

        for(Product product : listOfProducts){
            if((product.getUnitPrice().compareTo(high) < -1) && (product.getUnitPrice().compareTo(high)== 0) && (product.getUnitPrice().compareTo(low) > 1) && (product.getUnitPrice().compareTo(low)==0)){
                productsByPriceFilter.add(product);
            }
        }
        return productsByPriceFilter;
    }

这是我的服务(ProductService)

public interface ProductService {
    List<Product> getProductsByPriceFilter(BigDecimal high, BigDecimal low);
}

这是我的服务实现(ProductServiceImpl),它由这个方法组成

public List<Product> getProductsByPriceFilter(BigDecimal high, BigDecimal low){
        return productRepository.getProductsByPriceFilter(high, low);
    }

最后是我的 ProductController

@RequestMapping("/products/test")
    public String getProductsByPriceFilter(@RequestParam("high") BigDecimal high, @RequestParam("low") BigDecimal low, Model model){
        model.addAttribute("product", productService.getProductsByPriceFilter(high, low));
        return "products";
    }

但是我不断得到空白页,其中没有我传入的所有数据的高或低数据。所以,我想 问题 出在 getProductsByPriceFilter 方法 InMemoryProductRepository class.

你的对比问题就在这里:

if((product.getUnitPrice().compareTo(high) < -1) && (product.getUnitPrice().compareTo(high)== 0) && (product.getUnitPrice().compareTo(low) > 1) && (product.getUnitPrice().compareTo(low)==0)){

不能说high的比较结果可以小于-1同时等于zero。相反,您需要 is or between two conditions or better <= 0 以及 low 的另一种方式,例如:

 if((product.getUnitPrice().compareTo(high) <= 0) && (product.getUnitPrice().compareTo(low) >= 0))