在Java开发中经常遇见集合与数组的互相切换,怎样实现呢,呵呵呵,非常easy:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Test {
/**
* 将Set集合转换为数组
*
* @author GaoHuanjie
*/
private static void setToArray(){
Set<String> setNames = new HashSet<String>();
setNames.add("欧阳一博");
setNames.add("东方弘一");
setNames.add("田中义一");
String [] arryNames= new String[setNames.size()];
setNames.toArray(arryNames);
for (String name:arryNames) {
System.out.println(name);
}
}
/**
* 将List集合转换为数组
*
* @author GaoHuanjie
*/
private static void listToArray(){
List<String> listNames = new ArrayList<String>();
listNames.add("欧阳一博");
listNames.add("东方弘一");
listNames.add("田中义一");
String [] arryNames= new String[listNames.size()];
listNames.toArray(arryNames);
for (String name:arryNames) {
System.out.println(name);
}
}
/**
* 将数组转换为List集合
*
* @author GaoHuanjie
*/
private static void arrayToList(){
String [] arryNames= {"欧阳一博","东方弘一","田中义一"};
List<String> listNames =Arrays.asList(arryNames);
for (String name:listNames) {
System.out.println(name);
}
}
public static void main(String[] args) {
setToArray();
listToArray();
arrayToList();
}
}
Java对数组的操作(二)——集合与数组的切换