In: Computer Science
java please
Write a program that creates an ArrayList and adds 5 circle objects to the list , and display all elements in the list by invoking the object’s toString() method.
According to the problem statement,
I have coded the program in Java with all conditions satisfaction.
Below are the Snippets:
Code Snippet:
Output Snippet:
Code in Text format:
import java.io.*;
import java.util.*;
class Circle
// created
class circle
{
int radius;
// circle radius
Circle(int a)
//
constructor to set circle's radius
{
this.radius=a;
}
public String toString()
// toString method to get circle radius
{
return "Radius: "+radius;
}
}
class demo
{
public static void main(String args[])
{
ArrayList<Circle> list=new
ArrayList<Circle>();
// created
an ArrayList of type Circle with radius
for(int
i=1;i<=5;i++)
// looping for 5 times to
store 5 circle objects into ArrayList
{
Circle c=new
Circle(i);
list.add(c);
//
appending Circle object into ArrayList
}
System.out.println("5 Circle
Objects are Created and Stored in ArrayList");
Iterator
itr=list.iterator();
//getting the Iterator
System.out.println("Values of
Circle Objects:");
while(itr.hasNext())
//check if iterator has the elements
{
System.out.println(itr.next().toString());
// printing Circle radius by invoking toString
method of Circle
}
}
}
I hope the above snippets and information will help you out!
Thank you!