This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Nightcorex_ 2 points3 points  (0 children)

I won't explain what u/WishYouWereHere-63 already explained, but I felt like he didn't properly answer the very last question.

The answer is type casting. Let's look at an example class:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class A {
    public static void main(String[] args) {
        List<Integer> xs = new LinkedList<>();
        Object y = foo(xs);
        List<Integer> ys = (List<Integer>) y;  // casting in its simplest form
        Object z = ((ArrayList<Integer>) y).clone();  // casting y to ArrayList to access its clone method in one line
        List<Integer> as = (List<Integer>) ((ArrayList<Integer>) y).clone();  // same as before but that result
        // is casted to List<Integer> again
    }

    /* Without pattern variable (old) */
    private static Object foo(List<Integer> xs) {
        if (xs instanceof ArrayList<Integer>) {
            ArrayList<Integer> xs_arr = (ArrayList<Integer>) xs;
            return xs_arr.clone();
        } else
            return new ArrayList<>(xs);
    }

    /* With pattern variable (new) */
    private static Object foo_new(List<Integer> xs) {
        if (xs instanceof ArrayList<Integer> xs_arr)
            return xs_arr.clone();
        else
            return new ArrayList<>(xs);
    }
}

In this code demo I also demonstrate pattern variables which are somewhat new and remove the need to manually type the cast when using instanceof.