Similarities and Differences in list toArray () and toArray (T [] a) Method
These two methods are the methods the List, all of these elements exported as an array , except that
1. output
toArray () method is derived Object type array ,
toArray (T [] a) is the method of deriving the specified type of the array
2. Return an array if the array of new generation
toArray () method returns the array is an array of newly generated
Note: for multiple use toArray () method to obtain an array of objects, to which a modification, without affecting other toArray () method to obtain an array of objects, but will not affect the data itself is stored in the list.
List<Integer> list = New ArrayList<>();
list.add(1);
list.add(2);
Object[] obj1 = list.toArray();
Object[] obj2 = list.toArray();
System.out.println(obj1==obj2); // false
toArray (T [] a) method returned array is an array of newly generated
List<String> list = new ArrayList<>();
list.add("hellow");
list.add("world!");
String[] str = list.toArray(new String[]{});
String[] str1 = list.toArray(new String[]{});
System.out.println(str==str1); //false
3. Application
For example, list elements of the collection needs to be converted into an array
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
String[] strNew = new String[list.size()];
//使用toArray()方法
Object[] obj = list.toArray();
for(int i = 0; i<obj.length;i++){
String str = (String) obj[i];
strNew[i]= str;
}
//使用toArray(T[] a)方法
String[] strT = list.toArray(new String[]{});
note:
String [] strNew = (String []) list.toArray (); it is too easy to make mistakes, the result will be a run error: "Exception in thread" main "java.lang.ClassCastException: [Ljava.lang. Object; can not be cast to [Ljava.lang.String; ", this will be the reason:
- Object [] can not be converted into String [] ; (here, said index has a value in the group do not directly translate)
- java in the cast only for a single object
- If required conversion must be taken out of each of these values transformed