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;}

0

1 Answer 1

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"));
                      }};
Sign up to request clarification or add additional context in comments.

2 Comments

Note that List.of returns an immutable list.
Thanks for the quick reply! it worked like a charm! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.