將一個Collection轉為陣列

weixin_33751566發表於2018-08-01

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ConvertingACollentionToAnArray {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    List list = new LinkedList<>();
    // Create an array containing the elements in a list
    Object[] objectArray = list.toArray();
    MyClass[] array = (MyClass[]) list.toArray(new MyClass[list.size()]);

    Set set = null;
    // Create an array containing the elements in a set
    objectArray = set.toArray();
    array = (MyClass[]) set.toArray(new MyClass[set.size()]);

    Map map = null;
    // Create an array containing the keys in a map
    objectArray = map.keySet().toArray();
    array = (MyClass[]) map.keySet().toArray(new MyClass[set.size()]);

    // Create an array containing the values in a map
    objectArray = map.values().toArray();
    array = (MyClass[]) map.values().toArray(new MyClass[set.size()]);
}

}
class MyClass{}
Console:
這裡沒有給值,報空指標異常...

相關文章