Java等同于c#list声明

时间:2018-04-29 23:25:08

标签: java c# object variables

我想知道java中是否有相应的内容:

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

当然假设...有一个名为Person的类,其中包含{get; set;}

的FirstName和LastName字段

1 个答案:

答案 0 :(得分:3)

从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"));
                      }};