Saturday, March 9, 2024

Java Generics

In Java, you can use generics to create generic classes and methods, and you can also use varargs (variable-length argument lists) with generic types. Let's explore both concepts:

Generic Class:

public class Box<T> {

    private T content;

    public void setContent(T content) {

        this.content = content;

    }


    public T getContent() {

        return content;

    }


    public static void main(String[] args) {

        // Creating a generic Box for integers

        Box<Integer> intBox = new Box<>();

        intBox.setContent(42);

        System.out.println("Box content: " + intBox.getContent());


        // Creating a generic Box for strings

        Box<String> strBox = new Box<>();

        strBox.setContent("Hello, Generics!");

        System.out.println("Box content: " + strBox.getContent());

    }

}


In this example, the `Box` class is a generic class with a type parameter `T`. Instances of `Box` can be created for different types, such as `Integer` or `String`.

Variadic Generics (Generic and Varargs):

public class VarargsGenericExample {

    // Generic method with varargs

    public static <T> void printValues(T... values) {

        for (T value : values) {

            System.out.print(value + " ");

        }

        System.out.println();

    }


    public static void main(String[] args) {

        // Using varargs with different types

        printValues(1, 2, 3, 4, 5);

        printValues("apple", "banana", "orange");

        printValues(3.14, 2.71, 1.618);

    }

}

Method Generics 

In this example, the `printValues` method is a generic method that uses varargs to accept a variable number of arguments of type `T`. It can be called with different types, and the method will adapt accordingly.

You can combine generic classes with varargs methods or use varargs directly in generic methods to create flexible and reusable code in Java.


Certainly! In Java, you can create generic methods that introduce their own type parameters. Here's an example of a generic method:


public class GenericMethodExample {

    // Generic method that prints elements of an array

    public static <T> void printArray(T[] array) {

        for (T element : array) {

            System.out.print(element + " ");

        }

        System.out.println();

    }


    // Generic method that compares two objects of the same type

    public static <T extends Comparable<T>> int compare(T obj1, T obj2) {

        return obj1.compareTo(obj2);

    }


    public static void main(String[] args) {

        // Using the printArray generic method with different types

        Integer[] intArray = {1, 2, 3, 4, 5};

        String[] strArray = {"apple", "banana", "orange"};


        System.out.print("Integer array: ");

        printArray(intArray);


        System.out.print("String array: ");

        printArray(strArray);


        // Using the compare generic method with integers

        int result = compare(42, 24);

        System.out.println("Comparison result: " + result);


        // Using the compare generic method with strings

        result = compare("apple", "banana");

        System.out.println("Comparison result: " + result);

    }

}


In this example:

1. The `printArray` method is a generic method that can print elements of an array of any type.

2. The `compare` method is a generic method that compares two objects of the same type. The type parameter `T` is bounded by `Comparable<T>`, ensuring that the objects being compared implement the `Comparable` interface.


You can use generic methods to write reusable and type-safe code that works with different data types.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...