Which of the following are possible outputs of this application? (Choose all that apply)
0: import java.util.*; 1: class Shape {} 2: interface ShapeFactory { public java.util.List<Shape> getShapes(); } 3: public class Main { 4: public static void main(String[] args) { 5: ShapeFactory house = new MyShapeFactory(); 6: Shape chicken = house.getShapes().get(0); 7: for(int i=0; i<house.getShapes().size(); 8: chicken = house.getShapes().get(i++)) { 9: System.out.println("Shape"); 10: } 11: } 12:} 13:class MyShapeFactory implements ShapeFactory{ 14: public java.util.List<Shape> getShapes(){ 15: List<Shape> list = new LinkedList<>(); 16: list.add(new Shape()); 17: list.add(new Shape()); 18: list.add(new Shape()); 19: list.add(new Shape()); 20: list.add(new Shape()); 21: return list; 22: } 23:}
E
The code compiles without issue, so options A and B are incorrect.
house.getShapes() returns a list of multiple elements, the
code will output Shape
once for each element in the array, so option E is correct.
import java.util.LinkedList; import java.util.List; /* w w w . j a v a2 s.co m*/ class Shape { } interface ShapeFactory { public java.util.List<Shape> getShapes(); } public class Main { public static void main(String[] args) { ShapeFactory house = new MyShapeFactory(); Shape chicken = house.getShapes().get(0); for (int i = 0; i < house.getShapes().size(); chicken = house .getShapes().get(i++)) { System.out.println("Checken"); } } } class MyShapeFactory implements ShapeFactory { public java.util.List<Shape> getShapes() { List<Shape> list = new LinkedList<>(); list.add(new Shape()); list.add(new Shape()); list.add(new Shape()); list.add(new Shape()); list.add(new Shape()); return list; } }
The code above generates the following result.