在 HashSet 中传递方法是否是一个好习惯,如下所示,我直接在 HashSet 中传递方法?
Set byPrice = new HashSet(getProductsByPriceFilter( lowPrice, highPrice));**
public Set<Product> filterProducts(BigDecimal lowPrice,
BigDecimal highPrice, String manufacturer, String category) {
Set<Product> byPrice = new HashSet<Product>(getProductsByPriceFilter(
lowPrice, highPrice));
Set<Product> byManufacturer = new HashSet<Product>(
getProductsByManufacturer(manufacturer));
Set<Product> byCategory = new HashSet<Product>(
getProductsByCategory(category));
byPrice.retainAll(byManufacturer);
byPrice.retainAll(byCategory);
return byPrice;
}
最佳答案
对此的一个想法:如果您的方法已经返回可以填充整个 Set 的内容 - 为什么不让方法返回该 Set?
Set<Product> byPrice = getProductsByPriceFilter(
lowPrice, highPrice));
有一些
public Set <Product> getProductsByPriceFilter(double low, double high) {
其他过滤器也是如此。
或者...将已经过滤的集合传递到下一阶段。您可能在 getProductsByManufacturer ()
中对所有产品进行了循环。如果您添加已过滤的集合作为参数,您可以减少此循环以循环遍历已在价格范围内的所有产品等。
关于java - 在 HashSet 中传递方法是个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34781854/