import
java.util.ArrayList;
import
java.util.Arrays;
import
java.util.HashSet;
import
java.util.List;
import
java.util.Set;
/**
* 数组与Collection之间的转换
*/
public
class
ArrayCollection {
public
static
void
main(String[] args) {
List list =
new
ArrayList();
list.add(
"aaa"
);
list.add(
"bbb"
);
list.add(
"ccc"
);
list.add(
"ddd"
);
Object[] objArray = list.toArray();
System.out.println(
"从list转化成的对象数组的长度为: "
+ objArray.length);
String[] strArray1 = (String[])list.toArray(
new
String[
0
]);
System.out.println(
"从list转化成的字符串数组的长度为: "
+ strArray1.length);
String[] strArray2 = (String[])list.toArray(
new
String[list.size()]);
System.out.println(
"从list转化成的字符串数组的长度为: "
+ strArray2.length);
list.clear();
list =
new
ArrayList(Arrays.toList(strArray1))
System.out.println(
"从数组转化成的list的元素个数: "
+ objArray.length);
list.clear();
list = Arrays.asList(objArray);
System.out.println(
"从数组转化成的list的元素个数: "
+ objArray.length);
Set set =
new
HashSet();
set.add(
"aaa"
);
set.add(
"bbb"
);
objArray = set.toArray();
strArray1 = (String[])set.toArray(
new
String[
0
]);
strArray2 = (String[])set.toArray(
new
String[set.size()]);
set =
new
HashSet(Arrays.asList(objArray));
set.clear();
set.addAll(Arrays.asList(strArray1));
}
}