Questions On Generic Types in Java
Questions On Generic Types in Java
Objective:
● To implement generic types – generic classes and methods
Learning Outcomes:
● Learning to create a generic class and method
● Use the generic class to store/manipulate elements of different data types
Best Practices:
● Class Diagrams
● Proper naming conventions
● Comments at proper places
● Prompt messages during reading input and displaying output
● Modularity
● Coverage of test cases
Questions:
1. Write a Java program that defines a generic type MyLinkedList. The nodes in
the linked list should be capable of holding dataofanyofthefollowingtypes:
Integer, Double, Character, String. You should define functions to achieve the
functionality specified below:
a. Add new nodes: If a position is specified, then the new nodeshouldget
addedimmediatelyafterthespecifiedposition.Ifnopositionisspecified,
then the node should get added as the last node in the list.
b. Remove nodes: If a position is specified, then the node at that position
shouldgetdeleted.Ifadatavalueisgiven,thenthefirstnodeholdingthat
data should get deleted.
c. Get data: The data at a given position should be returned.
2. W
rite a Java program that defines a generic type ShapeBox that is capable of
holding different types of shapes. The ShapeBox classshouldallowyoutoadd
s hapesofdifferenttypes(e.g.,Circle,Square,Triangle)andprovideamethodto
calculate the total area of all shapes in the box.
a. Shape - An abstract class representing a shape with anabstractmethod
doublegetArea() to calculate the area of the shape.
b. Circle - A class representing a circle, which is a subclass of Shape. It
should have a constructor thattakestheradius.Itshouldimplementthe
getAreamethod to calculate the area of the circle.
c. Rectangle-Aclassrepresentingarectangle,whichisasubclassofShape.
It should have a constructor that takes the length and width. It should
also implement thegetAreamethod to calculate the area of the rectangle.
d. ShapeBox<T> - A generic class that can hold shapes of any type T that
extendstheShapeclass.Itshouldhavemethodstoaddshapestothebox
and calculate the total area of all shapes in the box.
rite a Java program that demonstrates the usage of these classes by creating
W
aShapeBox, adding various shapes to it, and calculating the total area of all the
shapes in the box. Your program should output the total area of the shapes in
the box.
3. Write a Java program to perform a sorting operation on various types of
elements using a generic method.