【问题标题】: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"));
                          }};
    

    【讨论】:

    • 请注意,List.of 返回一个不可变列表。
    • 感谢您的快速回复!它就像一个魅力! :)
    猜你喜欢
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多