[英]How would I assign values to an object on creation, that takes String and ArrayList values as params?
我正在使用Spring的CommandLineRunner將初始數據集加載到數據庫中。 創建新對象時,該對象需要一些String值,然后是ArrayList值。 有沒有辦法在新對象聲明中初始化String值和ArrayList值的值?
我可以通過為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**));
為了使代碼成功運行,將NULL分配給ArrayList是可行的,但是我想做的是聲明ArrayList,類似於傳遞字符串常量的方式。
您可能要使用
Collections.emptyList();
要么
Collections.singletonList(value);
或者,如果您有多個值
Arrays.asList(„value1“, „value2”, ...);
或Java的最新版本(JDK11及更高版本)
List.of(„value1“, „value2“, ...);
使用所有這些方法,您需要知道返回的List
是不可變的事實。 在List
添加或刪除元素將導致UnsupportedOperationException
。 如果您想要一個可修改的List
,則可以簡單地使用ArrayList(Collection)
構造函數。
您可以使用Arrays.asList("val1", "val2",...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.