In Java, a generic class is a class that can work with different data types. This tutorial will guide you through creating a custom generic class in Java.

Why Use Generic Classes?

Generic classes provide several benefits:

  • Type Safety: They ensure that the data passed to the class is of the correct type.
  • Code Reusability: You can use the same class with different data types.
  • Performance: They can be more efficient than casting in some cases.

Creating a Generic Class

To create a generic class, you use the <T> syntax. Here's an example of a simple generic class:

public class Box<T> {
    T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

In this example, Box is a generic class with one type parameter T. You can use this class to store any type of object.

Using the Generic Class

Here's how you can use the Box class:

Box<Integer> integerBox = new Box<Integer>();
integerBox.set(10);
System.out.println("Integer: " + integerBox.get());

Box<String> stringBox = new Box<String>();
stringBox.set("Hello World");
System.out.println("String: " + stringBox.get());

As you can see, the Box class can be used with both Integer and String types.

Benefits of Generic Methods

Generic methods provide similar benefits to generic classes. Here's an example of a generic method:

public class GenericMethods {
    public static <T> void printArray(T[] arr) {
        for (T element : arr) {
            System.out.print(element + " ");
        }
        System.out.println();
    }

    public static void main(String a[]) {
        Integer[] intArray = {1, 2, 3, 4, 5};
        String[] stringArray = {"Hello", "World", "Java", "Programming"};

        printArray(intArray);
        printArray(stringArray);
    }
}

In this example, the printArray method is a generic method that can work with any type of array.

Conclusion

Creating and using generic classes and methods in Java can greatly improve the type safety and reusability of your code. For more information on generics, check out our Java Generics Tutorial.