0

i whould like to know if there is an equivalent in java to this:

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

Assuming, of course... there is a class called Person with FirstName and LastName fields with {get;set;}

Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28
AcidRod75
  • 187
  • 9

1 Answers1

5

From Java 9 you can write

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

From Java 5.0 you could write

// 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"));

From Java 1.4 you can write

// mutable list
List<Person> People = new ArrayList<Person>() {{
                          add(new Person("John", "Doe"));
                          add(new Person("Someone", "Special"));
                      }};
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130