将SelectItem []保存到List <hotel> object </hotel>

时间:2011-08-03 19:08:29

标签: java jsf

我有一个List <Hotel>对象,我需要将其保存到SelectItem[]个对象。我该如何编码?

public List <Hotel> hotel;
public SelectItem[] food;
// followed by getters and setters

我需要将hotel对象保存到food对象。我如何用Java编写代码?

1 个答案:

答案 0 :(得分:2)

使用构造函数构造具有所需值和标签的SelectItem个对象。例如,酒店id为价值,酒店name为标签。

food = new SelectItem[hotels.size()];

for (int i = 0; i < hotels.size(); i++) {
    Hotel hotel = hotels.get(i);
    food[i] = new SelectItem(hotel.getId(), hotel.getName());
}

顺便说一句,List<SelectItem>也支持<f:selectItems>。这更容易创建。

food = new ArrayList<SelectItem>();

for (Hotel hotel : hotels) {
    food.add(new SelectItem(hotel.getId(), hotel.getName()));
}

根据您的问题历史,

无关具体问题,您使用的是JSF 2.0。您可以直接在List<Hotel>中使用<f:selectItems>,而无需使用丑陋的SelectItem包装模型。另请参阅上一个问题:How to populate options of h:selectOneMenu from database?