Interview question
How do you create a generic class in Java? Java में generic class कैसे बनाएं?
Answer
// Generic class with a single type parameter T
class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
Box<String> stringBox = new Box<>();
stringBox.set('Hello');
String value = stringBox.get(); // no cast needed
Box<Integer> intBox = new Box<>();
intBox.set(42);
Integer num = intBox.get();
// Generic class with MULTIPLE type parameters
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
Pair<String, Integer> pair = new Pair<>('age', 30);
System.out.println(pair.getKey() + ': ' + pair.getValue()); // age: 30
// Common type parameter naming conventions:
// T - Type, E - Element, K - Key, V - Value, N - Number, R - Return type
// Generic class can have bounded type parameters too
class NumericBox<T extends Number> {
private T value;
public void set(T value) { this.value = value; }
public double doubleValue() { return value.doubleValue(); } // Number methods available
}// एक type parameter वाली generic class
class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
Box<String> stringBox = new Box<>();
stringBox.set('Hello');
String value = stringBox.get();
Box<Integer> intBox = new Box<>();
intBox.set(42);
// Multiple type parameters वाली generic class
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
Pair<String, Integer> pair = new Pair<>('age', 30);
System.out.println(pair.getKey() + ': ' + pair.getValue());
// Naming conventions: T, E, K, V, N, R
class NumericBox<T extends Number> {
private T value;
public void set(T value) { this.value = value; }
public double doubleValue() { return value.doubleValue(); }
}Was this answer clear?