简体   繁体   中英

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?

.Start by making your ArrayList generic on the type of the object added to it, ie 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();
}

Make a loop:

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

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