java再字符串组添加新元素,如何将一个字符串数组的元素添加到字符串数组列表?...

I am trying to pass a string array as an argument to the constructor of Wetland class;

I don't understand how to add the elements of string array to the string array list.

import java.util.ArrayList;

public class Wetland {

private String name;

private ArrayList species;

public Wetland(String name, String[] speciesArr) {

this.name = name;

for (int i = 0; i < speciesArr.length; i++) {

species.add(speciesArr[i]);

}

}

}

解决方案

You already have built-in method for that: -

List species = Arrays.asList(speciesArr);

NOTE: - You should use List species not ArrayList species.

Arrays.asList returns a different ArrayList -> java.util.Arrays.ArrayList which cannot be typecasted to java.util.ArrayList.

Then you would have to use addAll method, which is not so good. So just use List

NOTE: - The list returned by Arrays.asList is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll to add elements to it. So, then you would better go with the 2nd way as below: -

String[] arr = new String[1];

arr[0] = "rohit";

List newList = Arrays.asList(arr);

// Will throw `UnsupportedOperationException

// newList.add("jain"); // Can't do this.

ArrayList updatableList = new ArrayList();

updatableList.addAll(newList);

updatableList.add("jain"); // OK this is fine.

System.out.println(newList); // Prints [rohit]

System.out.println(updatableList); //Prints [rohit, jain]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值