Converting a Collection to an Array - Java Collection Framework

Java examples for Collection Framework:Collections Utility Methods

Description

Converting a Collection to an Array

Demo Code

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

public class Main {
  public static void main(String[] argv) {
    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;/*  www.ja  v  a  2s .  co  m*/
    // 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 {
}

Related Tutorials