Java Topic
Java Generics
Java Generics provide a way to create classes, interfaces, and methods with a placeholder for the type they operate on. This allows for type-safe code, enabling the use of different data types without sacrificing type checking at compile time.
1. Benefits of Generics
Generics offer several key benefits:
- Type Safety: Ensures that you catch type-related errors at compile time rather than at runtime.
- Code Reusability: You can write a single class or method that works with different types.
- Elimination of Type Casting: Reduces the need for explicit casting, making code cleaner and less error-prone.
2. Generic Classes
A generic class is defined with a type parameter. This type parameter can be used within the class to define the type of its fields, methods, and constructors.
Example: Generic Box Class
public class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello, Generics!");
System.out.println(stringBox.getContent());
Box<Integer> intBox = new Box<>();
intBox.setContent(100);
System.out.println(intBox.getContent());
}
}
This example demonstrates a generic Box class that can hold and operate on any type T.
3. Generic Methods
Generic methods are methods that introduce their own type parameters, independent of any class-level generic parameters.
Example: Generic Method
public class GenericMethodExample {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"A", "B", "C"};
printArray(intArray);
printArray(strArray);
}
}
This example demonstrates a generic method printArray that can print elements of any array type.
4. Bounded Types
Generics can also enforce constraints on the types that can be used as arguments. This is done using bounded type parameters.
Example: Bounded Type Parameter
public class BoundedTypeExample {
public static <T extends Number> void sum(T num1, T num2) {
System.out.println("Sum: " + (num1.doubleValue() + num2.doubleValue()));
}
public static void main(String[] args) {
sum(10, 20);
sum(5.5, 3.5);
}
}
This example demonstrates a generic method sum that only accepts arguments of types that are subclasses of Number.
Java Method References
Method references in Java provide a way to refer to methods without executing them. They are a shorthand notation for lambda expressions when the method is already defined. Method references are part of the Java 8 lambda expression feature and allow us to write more concise and readable code.
1. Types of Method References
There are four types of method references:
- Reference to a Static Method:
ClassName::staticMethodName
Example:
Function sqrtFunc = Math::sqrt;
This references the static methodMath.sqrt().
Reference to an Instance Method of a Particular Object:
object::instanceMethodName
Example:
Consumer printFunc = System.out::println;
This references the instance methodprintln()ofSystem.out.
Reference to an Instance Method of an Arbitrary Object of a Particular Type:
ClassName::instanceMethodName
Example:
Function lengthFunc = String::length;
This references thelength()method of theStringclass.- Reference to a Constructor:
ClassName::new
Example:
Supplier> listSupplier = ArrayList::new;
This references theArrayListconstructor.
2. Syntax of Method References
The syntax of method references is straightforward:
ClassName::methodName
The double colon :: operator separates the class or object name from the method name.
3. Using Method References with Functional Interfaces
Method references can be used wherever a lambda expression is expected, especially when the lambda is just calling an existing method. Functional interfaces such as Function, Supplier, Consumer, and Predicate can take advantage of method references.
Example:
// Without method reference
Function sqrtFunc1 = (n) -> Math.sqrt(n);
// With method reference
Function sqrtFunc2 = Math::sqrt;
4. Benefits of Method References
- Concise and Readable: Method references eliminate boilerplate code and make the code more concise.
- Reusability: Instead of writing a lambda from scratch, you can reuse existing methods.
5. Method Reference vs Lambda Expression
While method references and lambda expressions are often interchangeable, method references are more concise when you're simply invoking an existing method. If your lambda expression does anything other than calling a method, a full lambda expression is needed.
Comments (0)
No comments yet. Be the first to comment!