Foreach de java me sobre writes the objects

0

Friends, I have a foreach in java that runs through a list to fill another and send it to my jquery, but I realized that the for is overwriting the objects.

Ex:

listingMethod (id) [0]) = 'samsung' and listingMethod (id) [0]) = 'iPhone 6'

On the first round l_jQuery [0] = 'Samsung' ,

in the second round l_jQuery [0] = 'iPhone 6' and l_jQuery 1 = 'iPhone 6' . I leave you some images and my code. Greetings and thanks.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    HttpSession sesion = request.getSession(false);
    PrintWriter out = response.getWriter();
    int id_consumidor = Integer.parseInt(sesion.getAttribute("id_consumidor").toString());
    Gson gson = new Gson();
    Producto producto = new Producto();
    List<Producto> lista = new ArrayList<>();
    List<Producto> l = productoFacade.oferta_guardadas(id_consumidor);
    productoFacade.oferta_guardadas(id_consumidor);
    for (Producto p : l) {
        producto.setNombreProducto(p.getNombreProducto());
        producto.setIdProducto(p.getIdProducto());
        producto.setPrecioNormal(p.getPrecioNormal());
        producto.setPrecioOferta(p.getPrecioOferta());
        producto.setRutaImagen(p.getRutaImagen());
        lista.add(producto);
    }
    String json = gson.toJson(lista);
    out.print(json);
}
    
asked by Tomás Ignacio Torres Calderón 29.10.2017 в 02:30
source

1 answer

2

You are working with the same instance associated with the variable Producto producto and you are adding it multiple times to the list. This gives the impression that it is always the same data, and it happens that it is the same object.

Just change a position line:

//recomendación: declarar las variables en su ámbito más cerrado posible
//Producto producto = new Producto();
List<Producto> lista = new ArrayList<>();
List<Producto> l = productoFacade.oferta_guardadas(id_consumidor);
productoFacade.oferta_guardadas(id_consumidor);
for (Producto p : l) {
    Producto producto = new Producto();
    producto.setNombreProducto(p.getNombreProducto());
    producto.setIdProducto(p.getIdProducto());
    producto.setPrecioNormal(p.getPrecioNormal());
    producto.setPrecioOferta(p.getPrecioOferta());
    producto.setRutaImagen(p.getRutaImagen());
    lista.add(producto);
}
    
answered by 29.10.2017 в 02:33