Detailed explanation of the conversion between list, set and array in Java

The conversion between Java list, set and array mainly uses Apache Jakarta common 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); CollectionUtils. The implementation of the addall () method is very simple, just recycling the add () method of the collection.

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

import java. util. Arrays; String[] strArray = {"aaa","ccc"}; List strList = Arrays. asList(strArray); But arrays The list returned by the aslist () method cannot be an add object, because the implementation of this method uses the size of the array referenced by the parameter to an ArrayList of new.

★ collection to array directly uses the toarray() method of collection, which has two overloaded versions:

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

★ map to collection directly uses the values () method of map.

★ list and set conversion 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));

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>