1. 程式人生 > >Core Java (二十五) List與Array的相互轉化,Set與Array的相互轉換

Core Java (二十五) List與Array的相互轉化,Set與Array的相互轉換

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 = "";//例項域初始化	
}