Here’s a simple generic class that can store any type of data:
// A generic class that can store any type of data
class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
public class Main {
public static void main(String[] args) {
Box<Integer> intBox = new Box<>(123);
Box<String> strBox = new Box<>("Hello Generics!");
System.out.println(intBox.getValue()); // Output: 123
System.out.println(strBox.getValue()); // Output: Hello Generics!
}
}
Here, T is a placeholder for the type you want to use. When you create a Box<Integer>, T becomes Integer; for Box<String>, it becomes String.
You can also make methods generic:
public class Main {
// Generic method
public static <T> void printItem(T item) {
System.out.println("Item: " + item);
}
public static void main(String[] args) {
printItem(42); // Output: Item: 42
printItem("Java"); // Output: Item: Java
}
}
This method works with any type you pass to it because you're passing a T, a generic. A "T" can be a CollegeStudent, a FluffyUnicorn, a PepperoniPizza, whatever you want.
Java has primitive data types like int, double, and char. However, sometimes you need to use objects instead of primitives—for example, when working with collections like ArrayList. That’s where wrapper classes come in.
What Are Wrapper Classes?
Wrapper classes “wrap” primitive values in an object. The name of the wrapper class is, capitalized, the written-out name of the data type (as in, "Integer" or "Double", etc.)
You use wrapper classes whenever you need an object instead of a primitive.
You can’t use primitives in collections like ArrayList, as we've already seen. You must use their wrapper classes:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// ArrayList<int> numbers = new ArrayList<int>(); // Invalid!
ArrayList<Integer> numbers = new ArrayList<>(); // Valid!
numbers.add(10);
numbers.add(20);
System.out.println(numbers); // Output: [10, 20]
}
}
Here, Integer is used instead of int.
Autoboxing is when Java automatically converts a primitive to its wrapper class when needed. Unboxing is the opposite process by which Java automatically converts a wrapper object back to a primitive.
Integer myInt = 5; // Autoboxing: int to Integer
int num = myInt; // Unboxing: Integer to int
System.out.println(myInt); // Output: 5
System.out.println(num); // Output: 5
This makes it easy to switch between primitives and objects.
Generics make your code flexible and type-safe, letting you write reusable classes and methods.
Wrapper classes let you use primitive values as objects, especially useful in collections and when object methods are needed.
Java handles most conversions between primitives and wrapper classes automatically (autoboxing/unboxing).
These concepts are foundational for modern Java programming—mastering them will make your code safer, cleaner, and more powerful
No comments:
Post a Comment