gpt4 book ai didi

Java 相当于 C# 列表声明

转载 作者:行者123 更新时间:2023-12-01 17:51:01 25 4
gpt4 key购买 nike

我想知道 java 中是否有与此等效的内容:

List<Person> People = new List<Person>(){
new Person{
FirstName = "John",
LastName = "Doe"
},
new Person{
FirstName = "Someone",
LastName = "Special"
}
};

当然,假设...有一个名为 Person 的类,其 FirstName 和 LastName 字段带有 {get;set;}

最佳答案

从 Java 9 开始你可以编写

// immutable list
List<Person> People = List.of(
new Person("John", "Doe"),
new Person("Someone", "Special"));

从 Java 5.0 开始你可以编写

// cannot add or remove from this list but you can replace an element.
List<Person> People = Arrays.asList(
new Person("John", "Doe"),
new Person("Someone", "Special"));

从 Java 1.4 开始你可以编写

// mutable list
List<Person> People = new ArrayList<Person>() {{
add(new Person("John", "Doe"));
add(new Person("Someone", "Special"));
}};

关于Java 相当于 C# 列表声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com