Reputation: 3763
I have an arrayList where three objects are passed.
List lst = new ArrayList();
Here the instances are added through for loop
Circle c1 = new Circle();
lst.add(c1);
Triangle t1 = new Triangle();
lst.add(t1)
Now how can I use the indexOf
method or other way to find out which one is the circle, triangle and calculate the area of both and store it in an arraylist?
Upvotes: 2
Views: 594
Reputation: 880
public interface Shape {
Long area();
}
public class Circle implements Shape {
public Long area() {
return 0l; // your code here
}
}
Same for Triangle class, then calculate area and put in another list...(java 8)
ArrayList<Shape> shapes = new ArrayList<>();
shapes.add(new Circle());
shapes.add(new Triangle());
ArrayList<Long> areas = new ArrayList<>();
areas.addAll(shapes.stream().map(s -> s.area()).collect(Collectors.toList()));
Upvotes: 1
Reputation: 5657
If you know that you will be inserting the Circle
instances before the Triangle
instances, then you can use even indexes to retrieve the Circle
instances and odd indexes to retrieve the Triangle
instances. Otherwise, you can loop through the list, check if each object is an instance of either class (e.g obj instanceof Circle
) and then perform your area calculations.
for(Object obj : lst){
if(obj instanceof Circle){
Circle circle = (Circle)obj;
// Perform the area calculations here
}else if(obj instanceof Triangle){
Triangle triangle = (Triangle)obj;
// Perform the area calculations here
}
}
Upvotes: -1
Reputation: 520918
Assuming that the Circle
and Triangle
classes extend Shape
, you could try this:
List<Shape> lst = new ArrayList<Shape>();
Shape c1 = new Circle();
Shape t1 = new Triangle();
lst.add(c1);
lst.add(t1);
for (Shape shape : lst) {
if (shape instanceof Circle) {
// handle the circle
}
else if (shape instanceof Triangle) {
// handle the Triangle
}
}
Upvotes: 2