简体   繁体   中英

How would I assign values to an object on creation, that takes String and ArrayList values as params?

I am loading an initial dataset into a database using Spring's CommandLineRunner. When creating a new object, the object requires a few String values and then an ArrayList value. Is there a way to initialize the values for both the String values and the ArrayList values within the new object declaration?

I can successfully create the object by passing in null for the ArrayList but what I am trying to do is add in String literals within the declaration.

//declared constructor in the Person class.

public Person(String name, String address, ArrayList<String> values){}

//implemented method from CommandLineRunner within the DatabaseLoader class.

@Override
public void run(String... args) throw Exception {
    this.repo.save(new Person("Joe", "123 Main St",  **null**));

In order to have the code run successfully assigning null to the ArrayList works, but what I am trying to do is declare the ArrayList similar to how the String literals are passed on.

You might want to use

Collections.emptyList();

or

Collections.singletonList(value);

or, if you have multiple values

Arrays.asList(„value1“, „value2”, ...);

or with recent versions of Java (JDK11 and above)

List.of(„value1“, „value2“, ...);

With all of these methods you need to be aware of the fact that the returned List is immutable. Adding or removing elements to the List will result in an UnsupportedOperationException . If you want a modifiable List you can simply use the ArrayList(Collection) constructor.

您可以使用Arrays.asList("val1", "val2",...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM