Search code examples
javalistvisitor-pattern

Usage of List.of() in visitor Pattern


I was going through the Visitor Pattern example from Wikipedia and there is a small piece of code as an example. You can find it here.

If you scroll through the Java example section, the constructor of the Car() uses something called List.of().

As per the oracle documentation, List.of() creates an immutable list. The same piece of code does not seem to work in my personal IntelliJ workspace and there is no recognition of List.of(). Although, if I could replace it with a mutable list - something like -

this.elements = new ArrayList<CarElement>();
this.elements.add(new Wheel("front left"));
this.elements.add(new Wheel("front right"));
this.elements.add(new Wheel("back left"));
this.elements.add(new Wheel("back right"));
this.elements.add(new Body());
this.elements.add(new Engine());

I could get the same output. Is there something wrong I am doing? Has it got anything to do with my JDK version? My JDK version is 1.8.0_45.


Solution

  • This is because List::of was introduced in JDK 9. Since you are compiling on JDK 8, this will not work.

    Type Parameters:
    E - the List's element type
    Parameters:
    elements - the elements to be contained in the list
    Returns:
    a List containing the specified elements
    Throws:
    NullPointerException - if an element is null or if the array is null
    Since:
    9

    Notice at the bottom of the docs they have Since: <version>. This will tell you which version the method was added in