【问题标题】:Java equivalent to c# list declaration [duplicate]Java相当于c#列表声明[重复]
【发布时间】:2018-04-29 23:25:07
【问题描述】:
我想知道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
c#
object
variables
【解决方案1】:
从 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"));
}};