I’m quite new to Java and have come accross to a strange behaviour that I can not explain why this happens or where is the mistake in my code.
Here’s the code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
abstract class Shape {
public abstract void printMe(String no);
}
final class Circle extends Shape {
@Override
public void printMe(String no){
System.out.println("This is Circle no: " + no);
}
}
final class Square extends Shape {
@Override
public void printMe(String no) {
System.out.println("This is Square no: " + no);
}
}
final class Triangle extends Shape {
@Override
public void printMe(String no) {
System.out.println("This is Triangle no: " + no);
}
}
public class Foo {
private ArrayList<Shape> shapes;
public Foo(){
this.shapes = new ArrayList<Shape>();
this.shapes.add(new Circle());
this.shapes.add(new Square());
this.shapes.add(new Triangle());
}
public void printShapes(ArrayList<String> numbers){
for(String s:numbers){
Iterator<Shape> iter = this.shapes.iterator();
Shape shape = iter.next();
shape.printMe(s);
}
}
public static void main(String[] args) {
ArrayList<String> numbers = new ArrayList<String>(Arrays.asList("1", "2", "3"));
Foo foo = new Foo();
foo.printShapes(numbers);
}
}
The output I’d expect would be:
This is Circle no: 1
This is Square no: 2
This is Triangle no: 3
However, the output I get is:
This is Circle no: 1
This is Circle no: 2
This is Circle no: 3
What am I doing wrong?
Pull this line out of the loop: