Understanding Java Generics: Concepts, Benefits, Common Uses, and Custom Implementations
This article explains the purpose of Java generics, their advantages for type safety and code robustness, demonstrates typical generic interfaces and collections with code examples, and discusses detailed usage rules, inheritance behavior, shorthand syntax, and how to create custom generic classes and methods.
Generics are a type that can accept other data types, introduced to solve the problem of unsafe collections where the add() method accepts Object, leading to type inconsistencies during iteration.
By specifying a concrete type at compile time, generics improve program robustness, enforce type safety, reduce the need for casting, and increase efficiency.
Benefits of Using Generics
Enhances program robustness and standardization.
Compile‑time checking of element types, providing immediate error feedback.
Reduces the number of type conversions, improving performance.
Allows class declarations to define property types, method return types, and parameter types.
Example class using a generic type parameter E:
class Person<E> {
E s; // property type
public Person(E s) { this.s = s; }
public E f() { return s; } // return type
public void show() { System.out.println(s.getClass()); }
}Instantiating the generic class with specific types:
public static void main(String[] args) {
Person<String> person1 = new Person<>("xxxx");
person1.show();
Person<Integer> person2 = new Person<>(123);
person2.show();
}
// Output:
// class java.lang.String
// class java.lang.IntegerCommon Generic Usages
1. Defining Generic Interfaces
interface Im<U, R> {
void hi(R r);
void hello(R r1, R r2, U u1, U u2);
default R method(U u) { return null; }
}When implementing the interface, concrete types must be supplied for <U, R>, and the compiler enforces these constraints.
2. Generic Collections
Using generics with HashSet:
HashSet<Student> students = new HashSet<>();
students.add(new Student("Lazy", 21));
students.add(new Student("Happy", 41));
students.add(new Student("Beautiful", 13));
for (Student s : students) {
System.out.println(s);
}Using generics with HashMap:
HashMap<String, Student> hm = new HashMap<>();
hm.put("001", new Student("Happy", 21));
hm.put("002", new Student("Lazy", 32));
hm.put("003", new Student("Beautiful", 43));
Set<Map.Entry<String, Student>> entries = hm.entrySet();
Iterator<Map.Entry<String, Student>> it = entries.iterator();
while (it.hasNext()) {
Map.Entry<String, Student> e = it.next();
System.out.println(e.getKey() + " - " + e.getValue());
}Generics eliminate the need for explicit casting when retrieving keys and values.
Details of Generic Usage
1. Type Constraints in <>
After specifying a concrete type, the generic can accept that type or any of its subclasses.
P<A> ap = new P<>(new A());
P<A> ap1 = new P<>(new B()); // B extends A
class A {}
class B extends A {}2. Shorthand Syntax
P<A> ap = new P(new A());Custom Generics
1. Using Class‑Level Generic Types in Methods
public static void main(String[] args) {
U<String, Double, Integer> u = new U<>();
u.hi("hello", 1.0);
}
class U<X, Y, Z> {
public void hi(X x, Y y) {}
}2. Defining Generic Methods
class U<X, Y, Z> {
public <X, Y> void m1(X x, Y y) {}
}The compiler infers the appropriate types and performs autoboxing when necessary.
3. Common Pitfalls
Generic arrays cannot be instantiated because the component type is unknown at runtime (e.g., A[] a = new A[]; is illegal).
Static methods cannot use class‑level generic parameters because static members belong to the class, not to any instance.
Understanding these rules helps write safer, more maintainable Java code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
