Alejandro León
Alejandro León

Reputation: 13

How to get the atributes and values of an object that is inside an ArrayList?

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?

Upvotes: 1

Views: 58

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

.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();
}

Upvotes: 3

krzydyn
krzydyn

Reputation: 1032

Make a loop:

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

Upvotes: 1

Related Questions