0

Basically I have an ArrayList of Objects. There are different types of objects, such as Triangles, Rectangles, and Spheres. Each object has its own method, such as getArea, getPerimeter, and getVolume. These methods are different for each object. How do I iterate through the ArrayList to print out all of the methods of each object?

So say I start with a Triangle. How do I print its getArea and getPerimeter methods with a for loop and a switch block / if statement?

1
  • 2
    You can override 'toString()' to return the String version of the output of these methods. Commented Nov 18, 2014 at 1:34

4 Answers 4

1

You can use a simple for loop to iterate over your ArrayList, and then call the toString() method of the object:

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

To override the toString method of your class, just add the method, pretty simple:

class Rectangle
{
    //Member variables
    int width, height; //Example

    //Member functions
    getArea { ... }

    //toString
    public String toString()
    {
        return String.valueOf(getArea());
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Manually calling toString() is redundant. System.out.println() will call it for you.
0
for(int i=0; i<listOfObjects.length; i++) {
   Object obj = listOfObjects[i];

   if (obj instanceof Triangle) {
      Triangle t = (Triangle) obj;
      t.getArea();
   } else if (obj instanceof Rectangle) {
      Rectangle r = (Rectangle) obj;
      r.getPerimeter();
   } else {
      Sphere s = (Sphere) obj;
      s.getSomeOtherThing();
   }
}

4 Comments

Although this works, be warned that instanceof should be a last resort, since it will lead to code that is hard to maintain. It is usually possible to use method overriding to produce the desired results; see @srakvin's toString() suggestion.
Forgot to mention that it must be done without an enhanced for loop. What does the Triangle t = (Triangle) obj; mean?
Triangle t = (Triangle) obj; means casting from object of Object to object of Triangle. Just change the code to regular for loop if you can't use enhanced loop. I have change it for you :)
if you think my answer is helpful for you, could you please select my answer as the correct answer for your question? Just tick the sign beside my answer. Thank you :)
0

Check this. An alternative to instanceof operator

    ArrayList arr=new ArrayList();
    arr.add(new Traingle());
    arr.add(new Rectangle());
    arr.add(new Sphere());
    for(Object obj:arr){
        int value=0;
        switch (obj.getClass().getSimpleName()){
        case "Rectangle":
            value=((Rectangle) obj).getPerimeter();
            break;
        case "Traingle":
            value=((Traingle) obj).getArea();
            break;
        case "Sphere":
            value=((Sphere) obj).getVolume();
            break;
        default:
            break;
        }
        System.out.println("Object "+obj.getClass().getSimpleName()+":"+value);
    }

Comments

0

Why not use an Interface?

package com.spiderman;

public interface Shape {
    public void getArea();

    public void getPerimeter();

    public void getVolume();
}

package com.spiderman;

public class Rectangle implements Shape {
    @Override
    public void getArea() {
        System.out.println("area of Rectangle");
    }
    @Override
    public void getPerimeter() {
        System.out.println("perimiter of Rectangle");   
    }
    @Override
    public void getVolume() {
        System.out.println("volume of Rectangle");
    }
}

package com.spiderman;

public class Triangle implements Shape {
    @Override
    public void getArea() {
        System.out.println("area of Triangle"); 
    }
    @Override
    public void getPerimeter() {
        System.out.println("perimiter of Triangle");    
    }
    @Override
    public void getVolume() {
        System.out.println("volume of Triangle");   
    }
}

package com.prash;

public class Sphere implements Shape {
    @Override
    public void getArea() {
        System.out.println("area of Sphere");
    }
    @Override
    public void getPerimeter() {
        System.out.println("perimiter of Sphere");
    }
    @Override
    public void getVolume() {
        System.out.println("volume of Sphere");
    }
}


package com.spiderman;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Shape> list = new ArrayList<Shape>();

        list.add(new Rectangle());
        list.add(new Triangle());
        list.add(new Sphere());

        for (int i = 0; i < list.size(); i++) {
            Shape shape = list.get(i);
            shape.getArea();
            shape.getPerimeter();
            shape.getVolume();
            System.out.println("------------------");
        }
    }
}

OUTPUT:

area of Rectangle
perimiter of Rectangle
volume of Rectangle

area of Triangle
perimiter of Triangle
volume of Triangle

area of Sphere
perimiter of Sphere
volume of Sphere

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.