将string数组存入集合
时间: 2023-09-06 16:08:11 浏览: 52
可以使用Java中的ArrayList来存储string数组。首先创建一个ArrayList对象,然后使用Arrays.asList()方法将string数组转换为List对象,最后将List对象添加到ArrayList中。示例如下:
```
String[] arr = {"one", "two", "three"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(arr));
```
这样就可以将string数组存入集合中了。
相关问题
java将string集合存入数组
可以使用toArray()方法将string集合转换为数组。示例代码如下:
```
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> strList = new ArrayList<String>();
strList.add("Java");
strList.add("Python");
strList.add("C++");
strList.add("Ruby");
String[] strArr = strList.toArray(new String[strList.size()]);
System.out.println("String Array Elements:");
for(int i=0; i < strArr.length; i++) {
System.out.println(strArr[i]);
}
}
}
```
这个代码将会输出以下结果:
```
String Array Elements:
Java
Python
C++
Ruby
```
将数组的元素存入到Arraylist集合中重复的元素只存入一次
你可以通过遍历数组,将每个元素存入到 ArrayList 集合中,然后对于重复的元素只存入一次。
下面是一个示例代码:
```java
String[] array = {"a", "b", "c", "a", "d", "b"};
ArrayList<String> list = new ArrayList<>();
for (String element : array) {
if (!list.contains(element)) {
list.add(element);
}
}
System.out.println(list);
```
其中,`contains()` 方法用于判断 ArrayList 集合中是否已经包含该元素,如果不包含则将其添加到集合中。
输出结果为:
```
[a, b, c, d]
```
可以看到,重复的元素 "a" 和 "b" 只存入了一次。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)