Pattern matching is a powerful feature introduced in Java that allows you to simplify and enhance the readability of your code. Initially introduced in Java 14 for instanceof checks and extended in later versions, pattern matching enables more expressive and concise code by reducing boilerplate.
Pattern matching allows you to extract components from objects and apply certain conditions in a concise manner. It is a feature that checks a value against a pattern and, if the match is successful, binds variables from the pattern.
One of the most common uses of pattern matching is with the instanceof operator. Here’s an example:
public class PatternMatchingExample { public static void main(String[] args) { Object obj = "Hello, World!"; if (obj instanceof String s) { System.out.println("The string is: " + s); } else { System.out.println("Not a string"); } } }
In this example, the instanceof operator not only checks if obj is a String but also casts it to a String and binds it to the variable s in a single step.
Pattern matching is also used with switch expressions, enhancing their power and flexibility. Here’s an example using sealed classes:
public sealed class Shape permits Circle, Rectangle, Square {} public final class Circle extends Shape { private final double radius; public Circle(double radius) { this.radius = radius; } public double radius() { return radius; } } public final class Rectangle extends Shape { private final double width, height; public Rectangle(double width, double height) { this.width = width; this.height = height; } public double width() { return width; } public double height() { return height; } } public final class Square extends Shape { private final double side; public Square(double side) { this.side = side; } public double side() { return side; } } public class PatternMatchingWithSwitch { public static void main(String[] args) { Shape shape = new Circle(5); String result = switch (shape) { case Circle c -> "Circle with radius " + c.radius(); case Rectangle r -> "Rectangle with width " + r.width() + " and height " + r.height(); case Square s -> "Square with side " + s.side(); }; System.out.println(result); } }
In this example, the switch expression uses pattern matching to destructure the Shape objects and extract relevant data.
Pattern matching in Java brings a new level of expressiveness and simplicity to your code. By reducing boilerplate and enhancing readability, it allows you to write cleaner and more maintainable programs. Whether you are working with complex data structures or simply trying to streamline your type checks, pattern matching is a valuable tool in your Java toolkit.
The above is the detailed content of Understanding Pattern Matching in Java. For more information, please follow other related articles on the PHP Chinese website!