Standard Libraries:
[Link] Ugale,CSE,COEPTECH
Collections in Java
• Collections are one of the most powerful and widely used features
in Java.
• They provide a framework to store, manipulate, and process
groups of objects efficiently.
• The Java Collections Framework (JCF) was introduced in Java 2
(JDK 1.2) to provide a consistent way to work with different types
of data structures like lists, sets, queues, and maps.
[Link] Ugale,CSE,COEPTECH
What is a Collection in Java?
• A Collection is an object that represents a group of individual
objects as a single unit.
• It is used to store, retrieve, manipulate, and communicate
aggregate data.
• Collections allow dynamic resizing, sorting, searching, and easy
manipulation of data.
[Link] Ugale,CSE,COEPTECH
Why Collections are Needed
• Java only supported arrays to store group of objects.
• Arrays had fixed size — you could not change the size dynamically.
• Arrays allowed storing elements of the same type only.
• Arrays lacked built-in methods for operations like sorting,
searching, etc.
[Link] Ugale,CSE,COEPTECH
After Collections:
• Collections are resizable — dynamic memory allocation.
• Collections can store heterogeneous objects.
• Collections provide built-in methods for:
• Sorting
• Searching
• Adding
• Removing
• Updating
[Link] Ugale,CSE,COEPTECH
Hierarchy of Java Collections Framework
• Java Collections Framework includes the following core interfaces:
• Collection Interface:
• List
• Set
• Queue
• Map Interface (Part of the framework but not directly extending
Collection)
[Link] Ugale,CSE,COEPTECH
[Link] Ugale,CSE,COEPTECH
1. Iterable Interface
• Iterable<T> is the root interface for all collection classes.
• It provides an iterator to iterate over the collection.
[Link] Ugale,CSE,COEPTECH
• Collections class in Java is one of the utility classes in Java
Collections Framework.
• The [Link] package contains the Collections class in Java. Java
Collections class is used with the static methods that operate on
the collections or return the collection.
• All the methods of this class throw the NullPointerException if the
collection or object passed to the methods is null.
[Link] Ugale,CSE,COEPTECH
• Example 1: Here, we will use ArrayList, which is a class from the Java Collections
framework.
• It allows to store elements in a list by maintaining the insertion order and also allows
duplicates.
• import [Link];
• public class demo {
• public static void main(String[] args) {
• // Create an ArrayList to store elements
• ArrayList<String> al = new ArrayList<>();
• // Add elements to the list
• [Link]("Apple");
• [Link]("Banana");
• [Link]("Apple"); // Duplicates are allowed
• [Link]("" + al);
• }
• }
[Link] Ugale,CSE,COEPTECH
Collection Class Declaration
• public class Collections extends Object
• Collection Framework contains both classes and interfaces.
Although both seem the same but there are certain differences
between Collection classes and the Collections framework.
• The Collection classes in Java are mentioned below:
[Link] Ugale,CSE,COEPTECH
• 1. ArrayList
• ArrayList is a class implemented using a list interface, in that provides the functionality of a dynamic array where the size of the array is not fixed.
• Syntax:
• ArrayList<_type_> var_name = new ArrayList<_type_>();
• 2. Vector
• Vector is a Part of the collection class that implements a dynamic array that can grow or shrink its size as required.
• Syntax:
• public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess,
• Cloneable, Serializable
[Link] Ugale,CSE,COEPTECH
• 3. Stack
Stack is a part of Java collection class that models and implements
a Stack data structure. It is based on the basic principle of last-in-
first-out(LIFO).
• Syntax:
• public class Stack<E> extends Vector<E>
[Link] Ugale,CSE,COEPTECH
• 4. LinkedList
• LinkedList class is an implementation of the LinkedList data
structure. It can store the elements that are not stored in
contiguous locations and every element is a separate object with
a different data part and different address part.
• Syntax:
• LinkedList<_type_> var_name = new LinkedList<_type_>();
[Link] Ugale,CSE,COEPTECH
• 5. HashSet
• HashSet is implemented using the Hashtable data structure. It
offers constant time performance for the performing operations
like add, remove, contains, and size.
• Syntax:
• public class HashSet<E> extends AbstractSet<E> implements
Set<E>, Cloneable, Serializable
[Link] Ugale,CSE,COEPTECH
Java Collections Example
Examples of Collections Classes in Java are mentioned below:
• Adding Elements to the Collections
• Sorting a Collection
• Searching in a Collection
• Copying Elements
• Disjoint Collection
[Link] Ugale,CSE,COEPTECH
1. Adding Elements to the Collections Class
Object
• The addAll() method of [Link] class is used to add all the specified elements to the specified collection. Elements to be added may be specified
individually or as an array.
• import [Link];
• import [Link];
• import [Link];
• class Demo {kjl/q3
• public static void main(String[] args) {
•
• List<String> l = new ArrayList<>();
• // Adding elements to the list
• [Link]("Shoes");
• [Link]("Toys");
• // Add one or more elements
• [Link](l, "Fruits", "Bat", "Ball");
• for (int i = 0; i < [Link](); i++) {
• [Link]([Link](i) + " ");
• }
• }
• } [Link] Ugale,CSE,COEPTECH
Sorting a Collection
• Collections. Sort() is used to sort the elements present in the
specified list of Collections in ascending order.
[Link]() is used to sort in descending order.
[Link] Ugale,CSE,COEPTECH
• // Sorting a Collections using sort() method
• import [Link];
• import [Link];
• import [Link];
• class Demo {
• public static void main(String[] args) {
• List<String> l = new ArrayList<>();
• // Adding elements to the list
• // using add() method
• [Link]("Shoes");
• [Link]("Toys");
• // Adding one or more
• // element using addAll()
• [Link](l, "Fruits", "Bat", "Mouse");
• // Sorting according to default ordering
• // using sort() method
• [Link](l);
[Link] Ugale,CSE,COEPTECH
• // Printing the elements
• for (int i = 0; i < [Link](); i++) {
• [Link]([Link](i) + " ");
• }
• [Link]();
• // Sorting according to reverse ordering
• [Link](l, [Link]());
• // Printing the reverse order
• for (int i = 0; i < [Link](); i++) {
• [Link]([Link](i) + " ");
• }
• }
• }
[Link] Ugale,CSE,COEPTECH
• Bat Fruits Mouse Shoes Toys
• Toys Shoes Mouse Fruits Bat
[Link] Ugale,CSE,COEPTECH
3. Searching in a Collection
• [Link]() method returns the position of an
object in a sorted list.
• To use this method, the list should be sorted in ascending order,
otherwise, the result returned from the method will be wrong.
• If the element exists in the list, the method will return the position
of the element in the sorted list, otherwise, the result returned by
the method would be the – (insertion point where the element
should have been present if exist)-1).
[Link] Ugale,CSE,COEPTECH
• // Binary Search using [Link]()
• import [Link];
• import [Link];
• import [Link];
• public class Demo {
• public static void main(String[] args) {
• List<String> l = new ArrayList<>();
[Link] Ugale,CSE,COEPTECH
• // Adding elements to object
• // using add() method
• [Link]("Shoes");
• [Link]("Toys");
• [Link]("Horse");
• [Link]("Ball");
• [Link]("Grapes");
• // Sort the List
• [Link](l);
• // BinarySearch on the List
• [Link](
• "The index of Horse is: "
• + [Link](l, "Horse"));
[Link] Ugale,CSE,COEPTECH
• // BinarySearch on the List
• [Link](
• "The index of Dog is: "
• + [Link](l, "Dog"));
• }
•}
• The index of Horse is: 2
• The index of Dog is: -2
[Link] Ugale,CSE,COEPTECH
4. Copying Elements
• The copy() method of Collections class is used to copy all the
elements from one list into another.
• After the operation, the index of each copied element in the
destination list will be identical to its index in the source list.
• The destination list must be at least as long as the source list. If it
is longer, the remaining elements in the destination list are
unaffected.
[Link] Ugale,CSE,COEPTECH
Collection Interface in Java
• The Collection interface in Java is a core member of the Java
Collections Framework located in the [Link] package.
• It is one of the root interfaces of the Java Collection Hierarchy.
• The Collection interface is not directly implemented by any class.
• It is implemented indirectly through its sub-interfaces like List,
Queue, and Set.
• For Example, the ArrayList class implements the List interface, a
sub-interface of the Collection interface.
[Link] Ugale,CSE,COEPTECH
• // Using the Collection interface with an ArrayList
• import [Link].*;
• public class Demo {
• public static void main(String[] args) {
•
• // Create a Collection using ArrayList
• Collection<String> c = new ArrayList<>();
•
• // Adding elements to the collection
• [Link]("Apple");
• [Link]("Banana");
• [Link]("Orange");
•
• [Link]("Collection: " + c);
• }
• }
[Link] Ugale,CSE,COEPTECH
Hierarchy of Collection Interface
[Link] Ugale,CSE,COEPTECH
The hierarchy also includes several key sub-interfaces:
• Iterable
• Collection
• List
• Set
• Queue
• The subInterfaces are sometimes called as Collection Types or
SubTypes of Collection.
• These include the following:
• 1. List
• The List interface represents an ordered collection that allows duplicates. It is
implemented by classes like ArrayList, LinkedList, and Vector. Lists allow
elements to be accessed by their index position.
• public interface List<E> extends Collection<E>
[Link] Ugale,CSE,COEPTECH
• 2. Set
• A set is an unordered collection of objects in which duplicate
values cannot be stored.
• This set interface is implemented by various classes like HashSet,
TreeSet, LinkedHashSet, etc.
• public interface Set<E> extends Collection<E>
[Link] Ugale,CSE,COEPTECH
• [Link]:
• The Queue interface represents a collection that follows FIFO
(First-In-First-Out) order.
• It is implemented by classes like PriorityQueue, Deque,
ArrayDeque, etc.
• public interface Queue<E> extends Collection<E>
[Link] Ugale,CSE,COEPTECH
Packages in Java
• A package in Java is a group of related classes and interfaces that
are bundled together for better organization, access control, and
code reuse.
• Think of it as a folder on your computer that contains related Java
files.
[Link] Ugale,CSE,COEPTECH
Types of Packages in Java
• Java has two types of packages:
• Built-in Packages → Provided by Java (e.g., [Link], [Link]).
• User-defined Packages → Created by developers.
• Built-in Packages in Java:
• Java provides many pre-defined packages that help in development and
utility functions.
[Link] Ugale,CSE,COEPTECH
Example:Using Built-in Packages
• import [Link];
• public class BuiltInPackageExample {
• public static void main(String[] args) {
• ArrayList<String> list = new ArrayList<>();
• [Link]("Java");
• [Link]("Python");
• [Link](list);
• }
• }
[Link] Ugale,CSE,COEPTECH
User-Defined Packages in Java
• Developers can create their own packages to group related
classes together.
• How to Create a Package:
1. Define the package name using the package keyword.
2. Save the file inside a folder with the same package name.
3. Use javac -d . [Link] to compile it.
4. Import and use the package in other Java files.
[Link] Ugale,CSE,COEPTECH
Step 1: Creating a Package
• package mypackage; // Declaring package
• public class Hello {
• public void sayHello() {
• [Link]("Hello from mypackage!");
• }
•}
• Save this file as [Link] inside a folder mypackage
[Link] Ugale,CSE,COEPTECH
Step 2: Compiling the Package
• Run the following command in the terminal:
• javac -d . [Link]
• The -d . option creates the mypackage directory and places the
compiled .class file inside it.
[Link] Ugale,CSE,COEPTECH
Step 3: Using the Package in Another Class
• import [Link]; // Importing user-defined package
• public class Test {
• public static void main(String[] args) {
• Hello obj = new Hello();
• [Link]();
• }
•}
[Link] Ugale,CSE,COEPTECH
Advantages of Using Packages
• Avoids name conflicts (two classes can have the same name in
different packages).
• Better organization of large codebases.
• Encapsulation and access control.
• Code reuse across multiple projects.
[Link] Ugale,CSE,COEPTECH
Disadvantages of Packages
• Slightly increases complexity for beginners.
• Needs proper directory structure for compilation.
[Link] Ugale,CSE,COEPTECH
Containers in Java
• In Java, containers are objects that store and manage multiple
components or objects.
• They provide a structured way to group, organize, and
manipulate data efficiently.
• Containers are widely used in GUI programming (Swing, JavaFX)
and in data structures (Java Collections Framework).
[Link] Ugale,CSE,COEPTECH
Types of Containers in Java
• Java containers can be broadly classified into two main
categories:
1. GUI Containers (Swing & AWT)
• Used in Graphical User Interfaces (GUI).
• Examples: JFrame, JPanel, JDialog, JApplet.
2. Data Structure Containers (Java Collections Framework)
• Used to store and manipulate data.
• Examples: ArrayList, HashMap, Stack, Queue.
[Link] Ugale,CSE,COEPTECH
GUI Containers in Java (Swing & AWT)
• ava provides GUI-based containers through AWT (Abstract
Window Toolkit) and Swing.
• These containers help in building Windows-based applications.
• Types of GUI Containers:
• 1. Top-Level Containers
• These are the main windows in a GUI application.
• JFrame → Main application window.
• JDialog → Popup dialog box.
• JApplet → Used for Java Applets.
[Link] Ugale,CSE,COEPTECH
2. Intermediate Containers
o Used to group components inside a top-level container.
o JPanel → Holds multiple components.
o JTabbedPane → Adds tabs to switch views.
3. Atomic Containers (Components)
o Basic UI elements like buttons, text fields, labels.
o JButton, JLabel, JTextField, JCheckBox, etc.
[Link] Ugale,CSE,COEPTECH
• import [Link].*;
• public class MyGUI {
• public static void main(String[] args) {
• JFrame frame = new JFrame("My Window"); // Create a JFrame container
• [Link](400, 300); // Set size
• [Link](JFrame.EXIT_ON_CLOSE); // Close when clicked
• JButton button = new JButton("Click Me"); // Add a button
• [Link](button); // Add button to frame
• [Link](true); // Show the window
• }
• }
• JFrame acts as a container that holds a JButton.
[Link] Ugale,CSE,COEPTECH
Data Structure Containers (Java Collections
Framework)
• Java Collections Framework (JCF) provides container classes
for data storage.
• Types of Data Structure Containers
[Link] Ugale,CSE,COEPTECH
• import [Link];
• public class ListContainerExample {
• public static void main(String[] args) {
• ArrayList<String> list = new ArrayList<>(); // Create an ArrayList (Container)
• [Link]("Apple");
• [Link]("Banana");
• [Link]("Cherry");
• [Link](list);
• }
• }
• ArrayList acts as a container that stores multiple strings.
[Link] Ugale,CSE,COEPTECH
Summary
• Containers in Java help in managing multiple components
efficiently.
• GUI containers manage UI elements in Swing & AWT applications.
• Data containers manage structured data using Java Collections
Framework.
• Understanding when to use which container helps in efficient
programming!
[Link] Ugale,CSE,COEPTECH
Generic Class in Java
• Generics in Java were introduced in Java 5 to provide type safety and
code reusability.
• Generics allow you to create classes, interfaces, and methods that
work with different data types while maintaining compile-time type
checking.
• Before Generics:
• Data structures like ArrayList, LinkedList, etc., stored objects of type
Object.
• This required explicit type casting when retrieving elements.
• No compile-time checking for type safety — could lead to
ClassCastException at runtime.
[Link] Ugale,CSE,COEPTECH
• With Generics:
• You can specify the type of data structures and objects.
• Type checking happens at compile-time, not at runtime.
• Reduces the risk of ClassCastException and increases code
reusability.
[Link] Ugale,CSE,COEPTECH
• Generic means parameterized types. Using generics, the idea is to
allow any data type to be it Integer, String, or any user-defined
Datatype and it is possible to create classes that work with
different data types.
• A Generic class simply means that the items or functions in that
class can be generalized with the parameter(example T) to specify
that we can add any type as a parameter in place of T like Integer,
Character, String, Double or any other user-defined type.
[Link] Ugale,CSE,COEPTECH
Example Without Generics (Before Java 5):
• Before Generics, Java used Object type to store data in collections like ArrayList:
• import [Link];
• public class WithoutGenerics {
• public static void main(String[] args) {
• ArrayList list = new ArrayList(); // No type safety
• [Link]("Java");
• [Link](100); // No compile-time error
• // Casting is required
• String s = (String) [Link](1); // Causes runtime error (ClassCastException)
• [Link](s);
• }
• }
[Link] Ugale,CSE,COEPTECH
Problems with this approach:
• No type checking at compile-time.
• Requires type casting.
• If the wrong type is inserted, it can cause a ClassCastException at
runtime.
[Link] Ugale,CSE,COEPTECH
Example With Generics (After Java 5):
• Generics solve these problems by allowing you to define the type at compile-time:
• import [Link];
• public class WithGenerics {
• public static void main(String[] args) {
• ArrayList<String> list = new ArrayList<>(); // Type-safe collection
• [Link]("Java");
• // [Link](100); // Compile-time error
• String s = [Link](0); // No need for type casting
• [Link](s);
• }
• }
[Link] Ugale,CSE,COEPTECH
Advantages of Using Generics:
• Type safety (compile-time checking)
• No need for type casting
• Code reusability
• Better performance due to early error detection
• Type Safety – Prevents insertion of incorrect types into collections or methods.
• Code Reusability – Same code works for different data types without rewriting.
• Eliminates Type Casting – No need to manually cast objects.
• Performance Improvement – Reduces runtime errors and improves efficiency.
[Link] Ugale,CSE,COEPTECH
How Generics Work
• Generics work by using type parameters (e.g., <T>).
• T – Stands for Type (you can use other symbols like E, K, V).
• Type parameters are replaced with actual data types at compile-
time.
[Link] Ugale,CSE,COEPTECH
Generics can be used in three main ways:
1. Generic Classes
2. Generic Methods
3. Generic Interfaces
[Link] Ugale,CSE,COEPTECH
Syntax of Generics
• Generic Class Syntax:
• class ClassName<T>
• {
• // T is a type parameter
• }
• Generic Method Syntax:
• <T> ReturnType methodName(T param)
• {
• // Method body
• }
[Link] Ugale,CSE,COEPTECH
• Generic Interface Syntax:
• interface InterfaceName<T> {
• T methodName(T param);
•}
[Link] Ugale,CSE,COEPTECH
Generic Class Example
• You can create a class that takes a type parameter <T>.
• class Box<T> {
• private T value;
• public void set(T value) {
• [Link] = value;
• }
• public T get() {
• return value;
• }
• }
[Link] Ugale,CSE,COEPTECH
• public class GenericClassExample {
• public static void main(String[] args) {
• // Integer type
• Box<Integer> intBox = new Box<>();
• [Link](100);
• [Link]([Link]());
• // String type
• Box<String> strBox = new Box<>();
• [Link]("Generics in Java");
• [Link]([Link]());
• }
• }
[Link] Ugale,CSE,COEPTECH
• <T> allows the class Box to handle any type (Integer, String, etc.).
• At compile-time, T is replaced with the actual type (Integer, String,
etc.).
• Provides type safety and prevents runtime type errors.
[Link] Ugale,CSE,COEPTECH
Generic Methods in Java
• A generic method allows type parameters to be defined at the method level
rather than the class level.
• Useful for methods that operate on different types, providing flexibility
without restricting the class to a specific type.
• Generic methods are defined with the syntax <T> before the return type.
• Syntax Example:
• public <T> void printArray (T[] array) {
• for (T element: array) {
• [Link](element);
• }
• }
[Link] Ugale,CSE,COEPTECH
Example: Generic Method in Java
• A generic method to print elements of any array type.
• public class GenericPrinter {
• // Generic method to print any type of array
• public static <T> void printArray(T[] array) {
• for (Telement: array) {
• ([Link](element + " ");
• }
• [Link]();
• }
• public static void main(String[] args) {
• Integer [] intArray = (1, 2, 3, 4);
• String[] stringArray("Java", "Generics",”Example”};
• [Link]("Integer Array: ");
• printArray(intArray);
• [Link]("String Array: ");
• printArray(stringArray);
• }
• }
[Link] Ugale,CSE,COEPTECH
• printArray is a generic method that takes an array of any type T and
prints its elements.
• The method works with both Integer [] and String[] arrays,
demonstrating its flexibility.
[Link] Ugale,CSE,COEPTECH
Bounded Types in Java Generics
• Bounded types allow us to restrict the type parameter to a specific
superclass or interface.
• Syntax:
• <T extends ClassName>
• restricts T to be of type ClassName or any of its subclasses.
• Supports both upper bounds (extends) and multiple bounds
(implements interfaces).
• Example: A method that accepts any subclass of Number.
• public <T extends Number> double add (Ta, Tb) {
• return [Link]() + [Link]();
•}
[Link] Ugale,CSE,COEPTECH
Wildcard Types in Java Generics
• Wildcard types allow a more flexible generic method or class definition, allowing an
unknown type to be specified with ?.
• Common wildcards include:
• ?: Unbounded wildcard (any type).
• ? extends T: Upper-bounded wildcard, any subtype of T.
• ? super T: Lower-bounded wildcard, any supertype of T.
• Example: Using an upper-bounded wildcard.
• public static void printNumbers (List<? extends Number> list) {
• for (Numbern: list) {
• [Link](n);
• }
• }
[Link] Ugale,CSE,COEPTECH
Example: Wildcard Types in Java Generics
• A method that prints elements of a list containing any subtype of Number.
• import [Link];
• public class WildcardExample :
• public static void printList (List<? extends Number> list) {
• for (Number n list) {
• [Link](n+ “”);
• }
• [Link]();
• public static void main(String[] args)
• {
• List<Integer> intList =[Link] (1, 2, 3, 4);
• List<Double> doublelist= [Link] (1.1, 2.2, 3.3);
• [Link]("Integer List: ");
• printList(intList);
• [Link]("Double List: ");
• printList (doublelist);
• }
• }
[Link] Ugale,CSE,COEPTECH
• The printList method accepts any List with a type that is a subclass of
Number.
• This provides flexibility while still enforcing type safety.
• Generics are enforced at compile-time but type information is erased at
runtime (type erasure).Ensures type safety, catching type errors at compile-
time.
• Ensures type safety with compile-time checks, but lacks some flexibility due
to type erasure(Java removes generic type information during compilation to ensure
backward compatibility with older versions of Java that do not support generics.) Generic
types are replaced with their raw types (e.g., T → Object).
• This techniques enable efficient and reusable code across multiple types,
each with unique trade-offs.
[Link] Ugale,CSE,COEPTECH
Understanding Generics with a Real-World
Example
• Let's assume we are designing a store inventory system that deals
with different types of products. We want to:
• Store multiple types of products (Books, Electronics, Clothing,
Food, Furniture, and Toys).
• Use a generic function to display product details.
• Use a generic class to store and retrieve different product types.
[Link] Ugale,CSE,COEPTECH
Implementing Generics in Java
• We will create:
• A generic class (Store<T>) to store different types of objects.
• Six different product classes (Book, Electronic, Clothing, Food,
Furniture, and Toy).
• A generic function to display details of any object.
[Link] Ugale,CSE,COEPTECH
Step 1: Creating a Generic Class Store<T>
• This class will store an object of any type T.
• // Generic class to store and retrieve any type of product
• class Store<T> {
• private T item;
• public Store(T item) {
• [Link] = item;
• }
• public T getItem() {
• return item;
• }
• public void setItem(T item) {
• [Link] = item;
• }
• }
• The class uses T (a type parameter) instead of a specific type.
• We can store any type in Store<T>, making it reusable.
[Link] Ugale,CSE,COEPTECH
Step 2:Creating Six Product Classes
1. Book Class
• Each class represents a different product type with attributes and a toString() method.
• class Book {
• String title;
• String author;
• public Book(String title, String author) {
• [Link] = title;
• [Link] = author;
• }
• @Override
• public String toString() {
• return "Book [Title: " + title + ", Author: " + author + "]";
• }
• }
[Link] Ugale,CSE,COEPTECH
2. Electronic Class
• class Electronic {
• String brand;
• double price;
• public Electronic(String brand, double price) {
• [Link] = brand;
• [Link] = price;
• }
• @Override
• public String toString() {
• return "Electronic [Brand: " + brand + ", Price: $" + price + "]";
• }
• }
[Link] Ugale,CSE,COEPTECH
3. Clothing Class
• class Clothing {
• String type;
• String size;
• public Clothing(String type, String size) {
• [Link] = type;
• [Link] = size;
• }
• @Override
• public String toString() {
• return "Clothing [Type: " + type + ", Size: " + size + "]";
• }
• }
[Link] Ugale,CSE,COEPTECH
[Link] Class
• class Food {
• String name;
• String expiryDate;
• public Food(String name, String expiryDate) {
• [Link] = name;
• [Link] = expiryDate;
• }
• @Override
• public String toString() {
• return "Food [Name: " + name + ", Expiry Date: " + expiryDate + "]";
• }
• }
[Link] Ugale,CSE,COEPTECH
5. Furniture Class
• class Furniture {
• String material;
• int weight;
• public Furniture(String material, int weight) {
• [Link] = material;
• [Link] = weight;
• }
• @Override
• public String toString() {
• return "Furniture [Material: " + material + ", Weight: " + weight + "kg]";
• }
• }
[Link] Ugale,CSE,COEPTECH
6. Toy Class
• class Toy {
• String name;
• int ageGroup;
• public Toy(String name, int ageGroup) {
• [Link] = name;
• [Link] = ageGroup;
• }
• @Override
• public String toString() {
• return "Toy [Name: " + name + ", Age Group: " + ageGroup + "+]";
• }
• }
[Link] Ugale,CSE,COEPTECH
• Each class has its own attributes and a toString() method to
display information.
• These classes will be stored in a generic store.
[Link] Ugale,CSE,COEPTECH
Step 3: Creating a Generic Function
• A generic function allows us to display details of any object.
• class Utility {
• public static <T> void displayDetails(T item) {
• [Link]([Link]());
• }
• }
• <T> makes the method generic.
• We can pass any type (Book, Electronic, etc.).
• The method prints the object details.
[Link] Ugale,CSE,COEPTECH
Step 4: Implementing the Main Method
• // Main class to test the generic programming implementation
• public class GenericDemo {
• public static void main(String[] args) {
• // Creating different product objects
• Book book = new Book("The Alchemist", "Paulo Coelho");
• Electronic laptop = new Electronic("Dell", 1200.99);
• Clothing shirt = new Clothing("T-Shirt", "L");
• Food apple = new Food("Apple", "2025-05-10");
• Furniture table = new Furniture("Wood", 25);
• Toy lego = new Toy("Lego Set", 6);
[Link] Ugale,CSE,COEPTECH
• // Using Generic Store class
• Store<Book> bookStore = new Store<>(book);
• Store<Electronic> electronicStore = new Store<>(laptop);
• Store<Clothing> clothingStore = new Store<>(shirt);
• Store<Food> foodStore = new Store<>(apple);
• Store<Furniture> furnitureStore = new Store<>(table);
• Store<Toy> toyStore = new Store<>(lego);
• // Displaying details using the generic function
• [Link]("=== Product Details ===");
• [Link]([Link]());
• [Link]([Link]());
• [Link]([Link]());
• [Link]([Link]());
• [Link]([Link]());
• [Link]([Link]());
• }
• }
[Link] Ugale,CSE,COEPTECH
Step 5: Output
• === Product Details ===
• Book [Title: The Alchemist, Author: Paulo Coelho]
• Electronic [Brand: Dell, Price: $1200.99]
• Clothing [Type: T-Shirt, Size: L]
• Food [Name: Apple, Expiry Date: 2025-05-10]
• Furniture [Material: Wood, Weight: 25kg]
• Toy [Name: Lego Set, Age Group: 6+]
[Link] Ugale,CSE,COEPTECH
• Generic Class (Store<T>): Stores different product types.
• Generic Function (displayDetails()): Prints any object’s details.
• Six Classes (Book, Electronic, etc.): Represent different products.
• Type-Safety: Ensures only valid types are used.
[Link] Ugale,CSE,COEPTECH