Home > Java > javaTutorial > body text

Detailed explanation of conversion between list, set and array in JAVA

高洛峰
Release: 2017-01-22 15:25:49
Original
1499 people have browsed it

JAVA’s conversion between list, set, and array mainly uses Apache Jakarta Commons Collections. The specific method is as follows:
import org.apache.commons.collections.CollectionUtils;

String[ ] strArray = {"aaa", "bbb", "ccc"};
List strList = new ArrayList();
Set strSet = new HashSet();
CollectionUtils.addAll(strList, strArray) ;
CollectionUtils.addAll(strSet, strArray);
The implementation of the CollectionUtils.addAll() method is very simple, it just uses the add() method of Collection in a loop.

If you just want to convert an array into a List, you can use the java.util.Arrays class in the JDK:

import java.util.Arrays;

String[] strArray = {"aaa", "bbb", "ccc"};
List strList = Arrays.asList(strArray);
However, the List returned by the Arrays.asList() method cannot add objects because of the implementation of this method It is an ArrayList that is new using the size of the array referenced by the parameter.

★ Collection to Array
Use Collection's toArray() method directly, which has two overloaded versions:

Object[] toArray();
T[] toArray(T[] a);

★ Map to Collection
Use Map’s values() method directly.

★ List and Set conversion
List list = new ArrayList(new Hashset());// Fixed-size list
List list = Arrays.asList(array);//Growable
list list = new LinkedList(Arrays.asList(array));// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

More lists in JAVA, For detailed information on conversion between set and arrays, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template