」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 了解 Java 中的模式匹配

了解 Java 中的模式匹配

發佈於2024-07-31
瀏覽:976

Understanding Pattern Matching in Java

模式匹配是 Java 中引入的一項強大功能,可讓您簡化程式碼並增強程式碼的可讀性。模式匹配最初在 Java 14 中引入用於 instanceof 檢查,並在以後的版本中進行了擴展,透過減少樣板檔案使程式碼更具表現力和簡潔性。

什麼是模式匹配?

模式匹配可讓您從物件中提取元件並以簡潔的方式應用某些條件。它是根據模式檢查值的功能,如果匹配成功,則綁定模式中的變數。

模式匹配的好處

  1. 簡潔程式碼:減少樣板程式碼,讓您的程式更短且更易於閱讀。
  2. 提高可讀性:透過使結構更加明顯來增強程式碼的清晰度。
  3. 型別安全:確保變數類型正確,減少執行階段錯誤的可能性。

使用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 工具包中的一個有價值的工具。

版本聲明 本文轉載於:https://dev.to/adaumircosta/understanding-pattern-matching-in-java-3f0k?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3