How to iterate through an array list of classes


How to iterate through an array list of classes


import java.util.ArrayList;

public class circleTester {

public static void showCenter(Circle2 circle) {
System.out.println(circle.getName() + "'s " + circle.getCenter());
}

public static void main (String args) {

ArrayList<Circle2> circles = new ArrayList<Circle2>();
circles.add(new Circle2(3, 5, 4));
circles.add(new Circle2(4, 2, 5));
circles.add(new Cylinder2(5, 2, 3, 5));
circles.add(new Cylinder2(3, 4, 7, 6));
circles.add(new Oval2(6, 5, 7, 3));
circles.add(new Oval2(4, 2, 3, 1));
circles.add(new OvalCylinder2(2, 3, 4, 5, 6));
circles.add(new OvalCylinder2(3, 3, 5, 4, 7));

for (Circle2 i : circles) {
showCenter(circles(i));
}
}
}



I have four separate classes: Circle2, Cylinder2, Oval2, and OvalCylinder2. They're all derived from Circle2, and OvalCylinder2. I'm trying to put them into an array list, and then iterate through the array list and run each instance through the showCenter function, which will call two getter (getName and getCenter) to tell you the class' name (Circle, Cylinder, Oval, and ovalCylinder), and where it's center is (x, y). However, in my for loop, I get an error:



"The method circles(Circle2) is undefined for the type circleTester"
How do I fix this?





Possible duplicate of How does the Java 'for each' loop work?
– OH GOD SPIDERS
Jun 29 at 15:33




2 Answers
2



Use showCenter(i) instead of showCenter(circles(i)) as i is already an object of Circle2 type


showCenter(i)


showCenter(circles(i))


i


Circle2


for (Circle2 circle : circles) {
showCenter(circle);
}



The syntax foreach loop syntax is:


for (T element : collection) {
...
}



Which reads as "for each T element in collection.". In your case i already has type of Circle2 and can be passed directly to showCenter method.


i


Circle2


showCenter


for (Circle2 circle : circles) {
showCenter(circle);
}



if you want to iterate over the list using indexes instead:


for (int i = 0; i < circles.size(); i ++) {
showCenter(circles.get(i));
}



the same can be achieved using an Iterator as well


for (Iterator<Circle2> i = circles.iterator(); i.hasNext(); )
showCenter(i.next())
}



and since java-8 there is a new forEach method available:


circles.forEach(cicle ->
System.out.println(circle.getName() + "'s " + circle.getCenter()))



which you can combine with labmda expression.



The latest version is arguably preferable if you are using java8+






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift