简体   繁体   中英

How do I print variable of object in collection in Java

Particle particle;

ArrayList<Particle>list = new ArrayList<Particle>();
for (int x=0; 100 > x; x++ ){
    list.add(new Particle(1,1,"1"));
}


for (int z = 0; 100 > z ; z++){
    System.out.println(list.get(z));
}

and i would Like to get something like this

System.out.println(list.get(z.variable) // which z is the particle ofc

I would also like to know how do i refer to this particles in collection, I would like to jump on this particles changing their values.

You just want:

for (Particle p : list) {
    System.out.println(p.variable);
}

or with the C-style for statement:

for (int i = 0 ; i < list.size() ; i++) {
    System.out.println(list.get(i).variable);
}

However, it's very atypical for a class to have public fields ("variables"), so I'm pretty sure you might have to access the variable with its getter, like so: list.get(i).getVariable() .

I'd suggest to read the source code of Particle.

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