简体   繁体   English

如何在创建时将值赋给对象,该对象将String和ArrayList值作为参数?

[英]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. 我正在使用Spring的CommandLineRunner将初始数据集加载到数据库中。 When creating a new object, the object requires a few String values and then an ArrayList value. 创建新对象时,该对象需要一些String值,然后是ArrayList值。 Is there a way to initialize the values for both the String values and the ArrayList values within the new object declaration? 有没有办法在新对象声明中初始化String值和ArrayList值的值?

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. 我可以通过为ArrayList传入null来成功创建对象,但是我想做的是在声明中添加String文字。

//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. 为了使代码成功运行,将NULL分配给ArrayList是可行的,但是我想做的是声明ArrayList,类似于传递字符串常量的方式。

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) 或Java的最新版本(JDK11及更高版本)

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

With all of these methods you need to be aware of the fact that the returned List is immutable. 使用所有这些方法,您需要知道返回的List是不可变的事实。 Adding or removing elements to the List will result in an UnsupportedOperationException . List添加或删除元素将导致UnsupportedOperationException If you want a modifiable List you can simply use the ArrayList(Collection) constructor. 如果您想要一个可修改的List ,则可以简单地使用ArrayList(Collection)构造函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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