模式匹配是java中引入的一项强大功能,可以让您简化代码并增强代码的可读性。模式匹配最初在 java 14 中引入用于 instanceof 检查,并在后续版本中进行了扩展,通过减少样板代码使代码更具表现力和简洁性。

什么是模式匹配?

模式匹配允许您从对象中提取组件并以简洁的方式应用某些条件。它是一项根据模式检查值的功能,如果匹配成功,则绑定模式中的变量。

模式匹配的好处

简洁代码:减少样板代码,使您的程序更短且更易于阅读。

提高可读性:通过使结构更加明显来增强代码的清晰度。

类型安全:确保变量类型正确,减少运行时错误的可能性。

使用instanceof进行模式匹配

模式匹配最常见的用途之一是使用instanceof 运算符。这是一个例子:

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");
    }
}

}
登录后复制

在此示例中,instanceof 运算符不仅检查 obj 是否为 string,还将其转换为 string 并一步将其绑定到变量 s。

使用 switch 表达式进行模式匹配

模式匹配还与 switch 表达式一起使用,增强了它们的功能和灵活性。这是使用密封类的示例:

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);
}

}
登录后复制

在此示例中,switch 表达式使用模式匹配来解构 shape 对象并提取相关数据。
立即学习“Java免费学习笔记(深入)”;

结论

java 中的模式匹配为您的代码带来了新的表现力和简单性。通过减少样板文件并增强可读性,它允许您编写更干净且更易于维护的程序。无论您是处理复杂的数据结构还是只是想简化类型检查,模式匹配都是 java 工具包中的一个有价值的工具。

    以上就是了解 Java 中的模式匹配的详细内容,更多请关注php中文网其它相关文章!