Write a program that contains a generics class with two type parameters.

3.A] Write a program that contains a generics class with two type parameters.

Answer:

Generics in Java:

Generics allow you to define classes, interfaces, and methods with type parameters, providing strong type-checking at compile time and eliminating the need for type casting. You can create generic classes with one or more type parameters.

Program with a Generic Class Having Two Type Parameters:

// Generic class with two type parameters T and U
class Pair<T, U> {
    private T first;
    private U second;

    // Constructor
    public Pair(T first, U second) {
        this.first = first;
        this.second = second;
    }

    // Getters
    public T getFirst() {
        return first;
    }

    public U getSecond() {
        return second;
    }

    // Setters
    public void setFirst(T first) {
        this.first = first;
    }

    public void setSecond(U second) {
        this.second = second;
    }

    // Display the pair
    public void display() {
        System.out.println("First: " + first + ", Second: " + second);
    }
}

public class GenericsExample {
    public static void main(String[] args) {
        // Creating a Pair object with Integer and String types
        Pair<Integer, String> pair1 = new Pair<>(1, "One");
        pair1.display(); // Output: First: 1, Second: One

        // Creating a Pair object with Double and Boolean types
        Pair<Double, Boolean> pair2 = new Pair<>(2.5, true);
        pair2.display(); // Output: First: 2.5, Second: true

        // Changing the values using setters
        pair1.setFirst(2);
        pair1.setSecond("Two");
        pair1.display(); // Output: First: 2, Second: Two
    }
}

Explanation:

Generic Class Pair<T, U>:

    • This class has two type parameters, T and U, which allow it to store a pair of objects of different types.
    • The class contains a constructor to initialize the two values, getters and setters for accessing and modifying the values, and a display() method to print the pair.

    Creating Instances:

      • In the GenericsExample class, two instances of Pair are created:
        • pair1 with Integer and String types.
        • pair2 with Double and Boolean types.
      • The program demonstrates how to create pairs of different types, display them, and modify their values using the setters.

      Summary:

      This program illustrates the use of a generic class with two type parameters in Java. It allows for the creation of flexible and reusable code that can work with different data types without sacrificing type safety.

      Leave a Reply

      Your email address will not be published. Required fields are marked *