In: Computer Science
In Java, what is the advantage of using ArrayList over arrays?
Write a program to perform following operations
a. Create a class named Rectangle with two
properties “height” and “width”. Create a parameterized
constructor to initialize “height” and “width” values.
b. Write method area() to calculate and return area of
Rectangle.
c. Create an ArrayList to store Rectangle objects.
d. Create three Rectangle objects of width and height set to
(2, 3), (3, 3) and (4, 5) and add them to ArrayList.
e. Calculate and print area of all the Rectangle objects in
ArrayList. (Hint: Area = height x width)
The advantages of using arrayList over arrays are as follows:
i) arrayList is resizable while arrays are of the fixed lenght,
with array you can not change the size of arrays once its
created.
ii) In arrayList, we have various types of methods to do
manipulation on objects.
iii) Multiple insertion and deletion can be done successfully from
arrayList.
iv) ArrayList can also be used to traverse in both the directions
of the list.
//class to get rectangle area
class GetRectangleArea
{
public static void main(String arg[])
{
Rectangle rectObj = new
Rectangle(10, 20);
System.out.println("Area
of Rectangle = " + rectObj.getArea());
//adding object to array list
ArrayList<Rectangle> rectList
= new ArrayList<Rectangle>();
rectList.add(rectObj);
}
}
//Rectangle class
class Rectangle
{
double height;
double width;
Rectangle(double hgt, double wdt)
{
this.height = hgt;
this.width = wdt;
}
double getArea()
{
return height *
width;
}
}