This feature was introduced in Java 14 and allows you to use the instanceof
operator in a more powerful and expressive way.
With pattern matching, you can use the instanceof
operator in combination with a variable declaration or assignment, and the compiler will automatically extract the value of the matched type and assign it to the variable.
Here’s an example of how to use pattern matching for instanceof
:
List<Object> items = Arrays.asList("Hello", 1, "world", 2);
for (Object item : items) {
if (item instanceof String s) {
System.out.println("String: " + s);
} else if (item instanceof Integer i) {
System.out.println("Integer: " + i);
}
}
In this example, we have a List
of Object
s that contains a mix of String
and Integer
values. We want to iterate through the list and perform different actions based on the type of the object.
Using pattern matching for instanceof, we can use the instanceof
operator in combination with a variable declaration, and the compiler will automatically extract the value of the matched type and assign it to the variable, in this case s
for String and i
for Integer. This way we can directly use the matched variable s
or i
to perform the actions we want.
Without pattern matching, we would have to use the traditional instanceof
operator and then use a separate casting statement, like this:
for (Object item : items) {
if (item instanceof String) {
String s = (String) item;
System.out.println("String: " + s);
} else if (item instanceof Integer) {
Integer i = (Integer) item;
System.out.println("Integer: " + i);
}
}
As you can see, in the above example, the code is more verbose and less readable. Also, if the casting statement is incorrect, it will throw a runtime exception, whereas the pattern matching feature is checked by the compiler, which can catch type errors at compile-time.
So, in this case, pattern matching makes the code more concise, readable, and less prone to errors.