我正在努力研究如何从充满对象的数组列表中获取属性。我想找到属于某一餐的所有菜肴,并按 dishType 过滤这些菜肴,并将它们显示在视图的表格中。所以我写了方法 getDishNameByType 但它会返回 null。任何帮助将不胜感激!Meal.Javapublic class Meal { @Id @GeneratedValue private Long id; @ManyToMany private Set<Dish> dishesList = new HashSet<>(); public String getDishNameByType(String dishType) { for (Dish dish : dishesList) { if (dishType == dish.getDishType()) { return dish.getDishName(); } } return null; }}Dish.Javapublic class Dish { @Id @GeneratedValue private Long id; private String dishName; private String dishType; @ManyToMany(mappedBy = "dishesList") private Set<Meal> mealsList = new HashSet<>();查看.html<tr th:if="${mealPage.empty}"> <td colspan="7" th:text="#{meals.list.table.empty}">No meals found</td></tr><tr th:each="meal : ${mealPage}"> <td th:text="${meal.id}">1</td> <td th:each="dish : ${meal.dishesList}" th:text="${meal.getDishNameByType("Maincourse")}"></td></tr>
1 回答
12345678_0001
TA贡献1802条经验 获得超5个赞
如果你有两个对象,obj1和obj2,那么obj1 == obj2当true且仅当这两个对象完全相同时。
String foo = "abc";
String bar = "abc";
boolean same = (foo == bar); //false
boolean similar = (foo.equals(bar)); //true
所以你需要打电话equals:
public String getDishNameByType(String dishType) {
for (Dish dish : dishesList) {
if ((dishType.equals(dish.getDishType()))) {
return dish.getDishName();
}
}
return null;
}
添加回答
举报
0/150
提交
取消