List.of() 在访客模式中的使用
Usage of List.of() in visitor Pattern
我正在浏览维基百科的访客模式示例,其中有一小段代码作为示例。
你可以找到它 here.
如果您滚动浏览 Java 示例部分,Car()
的构造函数会使用名为 List.of()
的东西。
根据 oracle documentation,List.of() 创建一个不可变列表。同一段代码在我个人的 IntelliJ 工作区中似乎不起作用,并且没有识别 List.of()
。
虽然,如果我可以用可变列表替换它 - 比如 -
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());
我可以获得相同的输出。我做错了什么吗?
跟我的JDK版本有关系吗?我的 JDK 版本是 1.8.0_45.
这是因为 List::of
是在 JDK 9 中引入的。由于您是在 JDK 8 上编译的,因此这将不起作用。
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
请注意文档底部有 Since: <version>
。这将告诉您该方法是在哪个版本中添加的
我正在浏览维基百科的访客模式示例,其中有一小段代码作为示例。 你可以找到它 here.
如果您滚动浏览 Java 示例部分,Car()
的构造函数会使用名为 List.of()
的东西。
根据 oracle documentation,List.of() 创建一个不可变列表。同一段代码在我个人的 IntelliJ 工作区中似乎不起作用,并且没有识别 List.of()
。
虽然,如果我可以用可变列表替换它 - 比如 -
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());
我可以获得相同的输出。我做错了什么吗? 跟我的JDK版本有关系吗?我的 JDK 版本是 1.8.0_45.
这是因为 List::of
是在 JDK 9 中引入的。由于您是在 JDK 8 上编译的,因此这将不起作用。
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
请注意文档底部有 Since: <version>
。这将告诉您该方法是在哪个版本中添加的