Java: Collection and Array transformations

Source: Internet
Author: User

List,set the method to convert to an array.
There are two forms of the ToArray function, one without parameters, one with parameters, and note the size of the array in the form of parameters.

Program code:

123456789
public void Convertcollectiontoarray () {List List = new ArrayList (); object[] ObjectArray1 = List.toarray (); string[] Array1 = List.toarray (New string[list.size ());  Set set = new HashSet (); object[] ObjectArray2 = Set.toarray (); string[] Array2 = Set.toarray (New string[set.size ());}

In turn, the array is converted to List,set.

12345
integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4}; To convert an array into a Set first we convert it to a List. Next//With the list we create a HashSet and pass the list as the constructor. List List = arrays.aslist (numbers); Set set = new HashSet (list);

Note : for int[] Arrays You cannot do this directly, because the parameters of the Aslist () method must be an object. Int[] should first be converted to integer[]. The same is true for arrays of other primitive types, which must first be converted to the corresponding array of wrapper types.

 12345678  
  int[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4}; int size = Numbers.length; integer[] array = new Integer[size];  for (int i = 0; i < numbers.length; i++) {integer integer = numbers[i];  Array[i] = integer;
  List List = arrays.aslist (array);  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.