Generic Programming in Java : Generics

Mannan Ul Haq
0

Generics in Java:

Generics are a powerful feature in Java that allow you to define type-safe data structures, without committing to actual data types. This leads to a high level of code reuse and increased readability. Generics are commonly used with collections and the methods that operate on them.

The basic syntax to define generics involves using angle brackets `<>` and place holders (like `T`), which act as a stand-in for any data type.

public class GenericClass<T> { ... }
public <T> void genericMethod(T parameter) { ... }

Here, `T` is the type parameter, which will be replaced by the actual data type when an instance of `GenericClass` is created or `genericMethod` is called.

Generic Methods:

Here's an example of a simple generic method:

static <T> void display(T item)
{
    System.out.println(item);
}

In this case, `T` is a placeholder for any type. This method can be used to display an item of any type:

display(5); // output: 5
display("Hello World"); // output: Hello World

Generic Classes:

A generic class can be defined in a similar way to a method. Here's an example:

class MyGenericClass<T>
{
    private T item;

    public void updateItem(T newItem)
    {
        item = newItem;
    }

    public T getItem()
    {
        return item;
    }
}

You can create an instance of this class using any data type:

MyGenericClass<Integer> myInt = new MyGenericClass<>();
myInt.updateItem(5);
System.out.println(myInt.getItem()); // output: 5

MyGenericClass<String> myString = new MyGenericClass<>();
myString.updateItem("Hello");
System.out.println(myString.getItem()); // output: Hello

Generic Class Methods:

You can also create generic methods within non-generic classes:

class MyClass
{
    public <T> T display(T value)
    {
        System.out.println(value);
        return value;
    }
}

You can call Display with any type:

MyClass myObject = new MyClass();
myObject.display(10);       // Output: 10
myObject.display("Hello");  // Output: Hello

Multiple Generic Arguments:

Both generic methods and classes can use multiple type parameters. Here is an example with a method:

public <T1, T2> void display(T1 value1, T2 value2)
{
    System.out.println(value1);
    System.out.println(value2);
}

You can call display with any types:

display(5, "Hello");  // Output: 5 Hello

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !