Logo
Unit 1 – Basic Generics in Java and Type Parameters

Basic Generics in Java and Type Parameters

Duration: 7 minutes

Hello, Java enthusiasts!

In this session, we delve into Generics in Java, a powerful feature that enables types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. Generics improve code reusability, type safety, and performance.

1. Understanding Generics

Generics allow you to define a common behavior for a variety of data types, reducing the need for code duplication. They enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods.

Example of a Generic Class:

java
Copy code
public class Box {
private T t; // T stands for "Type"
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
}

In this example, T is a type parameter that will be replaced by a real type when an object of Box class is created.

2. Using a Generic Class

Here’s how to use the Box class:

java
Copy code
public class Main {
public static void main(String[] args) {
Box integerBox = new Box<>();
Box stringBox = new Box<>();
integerBox.set(10); // Autoboxing of int to Integer
stringBox.set("Hello Generics");
System.out.println("Integer Value : " + integerBox.get());
System.out.println("String Value : " + stringBox.get());
}
}

In this example, Box is used with two different types: Integer and String.

3. Generic Methods

You can also write methods that have type parameters.

Example of a Generic Method:

java
Copy code
public class Util {
public static void printBoxContent(Box box) {
T content = box.get();
System.out.println("Box contains: " + content);
}
}

This method can print the content of a box, regardless of its type.

Exercise: Create a Generic Class and Methods

Now, let’s practice what you’ve learned. Create:

A generic class Pair with two type parameters, K and V (representing Key and Value). This class should store two objects: one of type K and one of type V.A generic method that accepts an object of Pair and prints the key and value.Conclusion

Well done! Generics are an essential aspect of Java, offering robustness and flexibility in your code. They enable you to write more general, reusable code and reduce runtime errors.

Experiment with generics to get a better grasp of how they can make your code more efficient and type-safe.

Happy coding, and enjoy exploring the world of Java Generics!

Next Tutorial: Multithreading and Concurrency in Java

7 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!