List與Array的相互轉化
List轉化成Array
調用了List的toArray方法,有兩個同名方法,其中Object[] toArray()返回一個Object類型的數組,但使用起來很不方便。另外一個是public <T> T[] toArray(T[] a),返回一個泛型數組T[].
Array轉化成List
調用了Arrays類的靜態方法asList,返回一個封裝了普通java數組的List封裝器。返回的對象不是ArrayList,而是一個視圖對象,實現了Serializable介面即可序列化,並且實現了RandomAccess介面。
例子:
package com.xujin;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class LinkedListTest{public static void main(String...arg){Employee jim = new Employee("Jim");Employee bob = new Employee("Bob");Employee gin = new Employee("Gin");/************List to Array********************************/List<Employee> staff = new ArrayList<Employee>();staff.add(jim);staff.add(bob);staff.add(gin);System.out.println(staff);//[Name:Jim, Name:Bob, Name:Gin]Employee[] e = new Employee[staff.size()];staff.toArray(e);for(Employee em : e)System.out.println(em);/* * Name:Jim * Name:Bob * Name:Gin * *//************Array to List********************************/List<Employee> arrayToList = Arrays.asList(e);System.out.println(arrayToList.get(2));//Name:Gin}}class Employee{public Employee(String name){this.name = name;}public String getName(){return this.name;}public String toString(){return "Name:" + name;}private String name = "";//執行個體域初始化}
Set與Array的相互轉換
與上面的相仿,Set轉化成Array是調用的toArray的泛型方法,而Array轉換成Set是調用的Array的asList方法。
例子:
此例子與上面的幾乎一樣,唯一的不同就是
/************Set to Array********************************/
Set<Employee> staff = new HashSet<Employee>();
結果也都一樣。
package com.xujin;import java.util.Arrays;import java.util.HashSet;import java.util.List;import java.util.Set;public class LinkedListTest{public static void main(String...arg){Employee jim = new Employee("Jim");Employee bob = new Employee("Bob");Employee gin = new Employee("Gin");/************Set to Array********************************/Set<Employee> staff = new HashSet<Employee>();staff.add(jim);staff.add(bob);staff.add(gin);System.out.println(staff);//[Name:Jim, Name:Bob, Name:Gin]Employee[] e = new Employee[staff.size()];staff.toArray(e);for(Employee em : e)System.out.println(em);/* * Name:Jim * Name:Bob * Name:Gin * *//************Array to Set********************************/List<Employee> arrayToList = Arrays.asList(e);System.out.println(arrayToList.get(2));//Name:Gin}}class Employee{public Employee(String name){this.name = name;}public String getName(){return this.name;}public String toString(){return "Name:" + name;}private String name = "";//執行個體域初始化}