all about generic in java
all about generic in java
Here, the class Box can store any type of object, and the
type T is determined when an object of the class is created
(e.g., Box<Integer> or Box<String>).
Why do we need Generics?
Type Safety: Generics enforce compile-time type checking,
ensuring that the correct type is used and reducing runtime errors.
Utility Classes:
When writing utility methods that operate on
collections or other types, generics help provide type
safety and reduce code duplication.
APIs:
When you design reusable APIs or libraries that must
work with a variety of types without knowing them in
advance.
Wildcards in Generics
Unbounded Wildcard (<?>)
<?> means any type can be used, and no restrictions are applied.
but it doesn't allow you to modify the elements of the collection.
You can read the elements, but you can’t insert new elements
because you don’t know the exact type.
Manjul Tamang
Software Developer
manjultamang.com.np