Questions
What are generics and why are they useful in Java?
The Scenario
You are a backend engineer at a fintech company. You are writing a new service that needs to work with a variety of different data types.
You could write a separate class for each data type, but this would be repetitive and would violate the DRY (Don’t Repeat Yourself) principle.
The Challenge
Explain what generics are in Java and how you would use them to solve this problem. What are the key benefits of using generics?
A junior engineer might not be aware of generics. They might try to solve this problem by using the `Object` class, which would not be type-safe.
A senior engineer would know that generics are the perfect tool for this job. They would be able to explain what generics are and how to use them to write type-safe code that can work with a variety of different data types.
Step 1: Understand What Generics Are
Generics are a feature of the Java language that allows you to write code that is type-safe and can work with a variety of different data types.
Step 2: Write a Simple Generic Class
Here’s how we can write a simple generic class to store a value of any type:
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
}In this example, T is a type parameter that can be replaced with any type.
Step 3: Use the Generic Class
We can use the generic class with any type:
Box<Integer> integerBox = new Box<Integer>();
integerBox.set(10);
Integer someInteger = integerBox.get();
Box<String> stringBox = new Box<String>();
stringBox.set("hello");
String someString = stringBox.get();The Benefits of Using Generics
| Benefit | Description |
|---|---|
| Type Safety | Generics provide compile-time type safety, which can help you to catch errors early. |
| Reusability | You can reuse the same generic class or method with a variety of different data types. |
| Readability | Generics make your code more readable by making it clear what types of data are being used. |
Practice Question
You want to write a generic method that can accept any type of `Number`. Which of the following would you use?