我尝试用Java解决List中的问题,但我无法解决。我有以下代码:
Productos producto = ... //come from a database, here there isn't errors
List<Productos> lista = new ArrayList<Productos>();
lista.set(0,producto);
我无法介绍&#39; producto&#39;在我的清单中,我不知道为什么。我曾尝试使用"lista.add(producto)"
,但它不起作用。我该怎么办?
Edit1:Producto不为null,它已初始化,并且它有一些具有正确值的属性。我也使用了lista.add(0,producto),但它没有工作:(。错误是:
Grave: java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at clientesCarrito.ClienteCarritoCompraServlet.doPost(ClienteCarritoCompraServlet.java:68)
是的,做了一个&#34;糟糕的演员&#34;看起来像是一个错误。对Int,但我不认为..这是我的代码的一部分:
EntityManager em = entityManagerFactory.createEntityManager();
.
.
int id = Integer.parseInt(request.getParameter("IdProd"));
Productos producto = em.find(Productos.class,id);
HttpSession session = request.getSession(false);
if(session.getAttribute("carProductos")==null){
List<Productos> lista = new ArrayList<Productos>();
lista.add(producto);
session.setAttribute("carProductos", lista);
}else{
List<Productos> lista = (List<Productos>) session.getAttribute("carProductos");
lista.add(producto);
session.setAttribute("carProductos", lista);
}
我已经在Eclipse和&#34; IdProd&#34;中完成了调试。是5和&#34; id&#34;也是5。现在它看起来像&#34; lista&#34;赶上&#34; producto&#34;并介绍自己,但当它在底部突然显示错误和崩溃。在此代码之后,我不再使用&#34; lista&#34;或&#34; producto&#34;。有人可以帮帮我吗?
答案 0 :(得分:1)
以下是java.util.ArrayList.add()方法的声明 public void add(int index,E element)
所以使用
lista.add(0, producto)
答案 1 :(得分:1)
在set
和List
之间的位置设置元素时,0
中的size() - 1
方法会引发错误。在空List
上,您永远不能set
元素。来自:https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set%28int,%20E%29
抛出: IndexOutOfBoundsException - 如果索引超出范围(索引&lt; 0 || index&gt; = size())
我想你想做的是在列表中添加一个元素;由于List
为空,因此唯一有效的位置为零:
lista.add(producto);
add
方法将元素添加到列表的末尾。在空列表的情况下,它将元素添加为唯一元素。