A probe into the usage of toarray in Java (Java Arrays and list conversions)

Source: Internet
Author: User

A. Incident

Import Java.util.ArrayList;

Import java.util.List;

public class Test {

public static void Main (string[] args) {

list<string> list = new arraylist<string> ();

List.add ("1");

List.add ("2");

String[] tt = (string[]) List.toarray (new string[0]);

}

}

This code is OK, but we see string[] tt = (string[]) List.toarray (new string[0]) The parameters are very strange, but remove this parameter new String[0] but run the times wrong ...

two. Root cause Analysis

The study found that ToArray has two methods:

Public object[] ToArray () {

Object[] result = new Object[size];

System.arraycopy (elementdata, 0, result, 0, size);

return result;

}

The ToArray method without parameters is a constructed object array and then a copy of the data, at which time the transformation will produce classcastexception, which is the root cause of the above problem.

Public object[] ToArray (Object a[]) {

if (A.length < size)

A = (object[]) java.lang.reflect.Array.newInstance (A.getclass (). Getcomponenttype (), size); System.arraycopy (elementdata, 0, a, 0, size);

if (A.length > Size)

A[size] = null;

return A;

}

The ToArray method with parameters, based on the type of the parameter array, constructs an empty array of the corresponding type, which is the same length as the size of ArrayList, although the method itself returns the result in the form of an object array. However, because the componenttype used in constructing arrays are consistent with the componenttype that need to be transformed, there is no transformation exception.

three. Solutions

So you can refer to the following three ways when using ToArray

1. long[] L = new Long[<total size>];

List.toarray (l);

2. long[] L = (long[]) List.toarray (new long[0]);

3. long[] A = new Long[<total size>];

Long[] L = (long[]) List.toarray (a);

Four. further consideration

The elements in the container have been restricted by generics, and the elements should be treated as generic types, but not in the current Java, when the direct string[] TT = (string[]) List.toarray (), run an error. Recall that the forced type conversion in Java is only for a single object, and to be lazy, it is not possible to convert the entire array into an array of another type, which is similar to the one that needs to be initialized.

Above from:http://hi.baidu.com/%b4%cb%d6%d0%d3%d0%d5%e6%b5%c0/blog/item/8add93ec812dc9deb31cb1b0.html

[Java]View Plain Copy
  1. Import java.util.*;
  2. Class testlist{
  3. public static void Main (string[] args) {
  4. list<character> list = new arraylist<character> ();
  5. string[] str = "a b C". Split ("");
  6. System.out.println ("string array str, Length:" + str.length);
  7. for (String c:str)
  8. System.out.println (c);
  9. list<integer> list = new arraylist<integer> ();
  10. List.add (1);
  11. List.add (2);
  12. List.add (3);
  13. List.add (4);
  14. Iterator<integer> it = List.iterator ();
  15. System.out.println ("integer list List");
  16. while (It.hasnext ())
  17. {
  18. System.out.println (It.next ());
  19. }
  20. Array into List
  21. list<string> li = new arraylist<string> ();
  22. Li = arrays.aslist (str);
  23. iterator<string> its = Li.iterator ();
  24. SYSTEM.OUT.PRINTLN ("Array str, list:");
  25. while (Its.hasnext ())
  26. {
  27. System.out.println (Its.next ());
  28. }
  29. List conversion Array
  30. Integer[] B = (integer[]) List.toarray (new integer[0]);
  31. SYSTEM.OUT.PRINTLN ("List-by-array B");
  32. for (Integer i:b)
  33. System.out.println (i);
  34. The Fill method of the array
  35. Int[] A = new int[5];
  36. Arrays.fill (a,0);
  37. SYSTEM.OUT.PRINTLN ("Array A is filled with 0");
  38. for (int i:a)
  39. System.out.println (i);
  40. }
  41. }

Top

A probe into the usage of toarray in Java (Java Arrays and list conversions)

Related Article

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.