简体   繁体   中英

Copy one item from an ArrayList to another ArrayList Java 8

I'm currently working on an uni project where I have a simple shop where I can create products, store them into an ArrayList , and then, I want to select some of those products and store them into another ArrayList . The idea is select a product (giving the index) from productList and store it on shoppingCartList .

What I currently have:

ArrayList<Producto> listaProductos = new ArrayList<>();
ArrayList<Pedido> listaPedido = new ArrayList<>();

I have already done the code for creating, removing, modifying and listing the products from listaProductos which is where I store all the products, so the only thing I need is a method to select a specific item given an index, and store to listaPedido , but I can't find a proper way to do that, I only know how to copy ALL the ArrayList to another.

So my question is, how to copy one item from an ArrayList to another?

You can use get() method to get a item at index from ArrayList

Producto product = listaProductos.get(index);

Where index is a integer

Use add() method to add it to second list , Since the second list is of type Pedido you can't add it unless it is of compatible type. You need to convert your Producto object to Pedido to do that you can create a new `Pedido' object and set all the attributes from the 'Producto' , if you have getters and setters you can do like this

Pedido pedido = new Pedido();
pedido.set...(product.get...()); //for all other fields 
listaPedido.add(pedido);

If getters and setters is not written and attributes are public you can directly assign like

pedido.attributeName = producto.attribute;

Take a look into documentation: ArrayList JavaDoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM