1

I have an ArrayList with many objets that have values:

miProductoAseo = new ArrayList(); miProductoAseo.add(new ProductoAseo(app, miAseo[0], miAseoPrecio[0], 430, 360, 8000)); miProductoAseo.add(new ProductoAseo(app, miAseo[1], miAseoPrecio[1], 675, 360, 25000)); miProductoAseo.add(new ProductoAseo(app, miAseo[2], miAseoPrecio[2], 920, 360, 5500)); 

I need to retrieve some of the values im giving to the objects. For example, the last value of each object is a price (8000,25000 and 5500), and I need to make a sum with those values: 8000 + 25000 + 5500 = 38500.

How can I achieve this?

2
  • Will all references added to the ArrayList be type ProductoAseo? Commented Aug 30, 2015 at 0:20
  • Yes, that ArrayList only has ProductoAseo Objects. Commented Aug 30, 2015 at 0:32

2 Answers 2

3

.Start by making your ArrayList generic on the type of the object added to it, i.e. ProductoAseo. This would let you access product's properties without a cast.

Then make a loop adding up properties of ProductoAseo:

List<ProductoAseo> miProductoAseo = new ArrayList<ProductoAseo>(); miProductoAseo.add(new ProductoAseo(app, miAseo[0], miAseoPrecio[0], 430, 360, 8000)); miProductoAseo.add(new ProductoAseo(app, miAseo[1], miAseoPrecio[1], 675, 360, 25000)); miProductoAseo.add(new ProductoAseo(app, miAseo[2], miAseoPrecio[2], 920, 360, 5500)); int sum = 0; for (ProductoAseo p : miProductoAseo) { sum += p.price(); } 
Sign up to request clarification or add additional context in comments.

4 Comments

If you are using Java 8, you could simplify the for loop further miProductoAeso.forEach(p -> sum += p.price())
@Rishabh You are absolutely right. However, I think this may be too advanced for OP's level at the moment.
Ill try the way dasblink does it.
@AlejandroLeón You are welcome! If you are not looking for additional help with this question, consider accepting an answer by clicking the grey check mark next to it. This would let other site visitors know that the answer has worked for you, and earn you a new badge on Stack Overflow.
1

Make a loop:

int sum=0; for (ProductoAseo pa : miProductoAseo) sum+=pa.price; System.out.println(sum); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.