更改列表类型<String>

change type of List<String>

我想将类型为 arrayList 的产品的值插入数据库,但出现此错误 "java.lang.String cannot be cast to model.Product"。问题在于我在 servlet 中所做的转换。这是它的代码:

String buyer = request.getParameter("buyer");
List<String> prodlist = Arrays.asList(request.getParameterValues("product"));

List<Product> prodmlist = (List<Product>) (List<?>) prodlist;
Bill bill = new Bill(buyer, prodmlist);
myDAO.add(bill);

这是将要填充的方法

public static void add(Bill bill) {
Connection cnx;
    try {
    cnx = Connect.getConnection();
    String req = "insert into bil values (?,?)";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, bill.getBuyer());
    for (Product prod : bill.getProduct()) {
        st.setString(2, prod.getName());
        st.addBatch(); // add the statement to the batch
    }
    st.executeUpdate();    
    cnx.commit();
}

在您的代码中:

List<String> prodlist = Arrays.asList(request.getParameterValues("product"));
// Need to convert here...
List<Product> prodmlist = (List<Product>) (List<?>) prodlist;

您需要明确地将 List<String> 转换为 List<Product>。按照以下方式做一些事情:

List<Product> products = new ArrayList<Product>();
for (String s: prodList){
    Product p = new Product();
    p.setName(s);
    products.add(p);
}

现在,我假设您有 setter 来设置产品名称。可能是您有一个可以将名称传递给的构造函数(并保存一行代码)。

您不能将列表从一种类型转换为另一种类型。如果你想 "change the type" 你必须转换它 :

使用 Java 8 λ:

listReceived.forEach(string -> listProduct.add(new Product(string)));

通常的方式:

for (String string : listReceived) {
        listProduct.add(new Product(string));
}

我假设您的 class 产品有一个接受字符串的构造函数。如果不是,您应该解析字符串并在循环中完成产品的每个成员。

// expecting that all information are separated by a space
Product product = new Product();
String[] splittedString = string.split(" ");
product.name = splittedString[0];
....
listProduct.add(product);