[英]Create a ArrayList in the constructor in java
我正在練習訪客模式。 我發現了一些有趣的事情,程序在構造函數中創建了一個新的 ArrayList,這讓我很困惑。
例如:
class Computer implements ComputerPart
{
List<ComputerPart> parts;
public Computer(){
parts = new ArrayList<>(List.of(
new Mouse(),
new Keyboard(),
new Monitor()
));
}
是否等於:
class Computer implements ComputerPart
{
List<ComputerPart> parts = new ArrayList<>(List.of(
new Mouse(),
new Keyboard(),
new Monitor()
));
public Computer(){
}
這是否意味着在創建新Computer
時,它將具有Keyboard
、 Mouse
和Monitor
的新 ArrayList? 非常感謝任何幫助。
結果是一樣的。
雖然這里不需要,但是在構造函數中初始化字段的好處是:
在字段聲明中初始化字段的好處是:
對於問題中的代碼,可以通過任何一種方式完成。 內聯會更簡潔,但使用構造函數並沒有錯,只是另一種方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.