converting hashmap to stringarray

DrWooolie picture DrWooolie · Aug 22, 2012 · Viewed 10.4k times · Source

I am trying to convert a hashmap into an array, that I can put in a created string array. I however get java.lang. I have typeconverted my drinkar.keySet().toArray() to String[], but it will still not work.

public String[] receiveArrayList(){

String[] list = new String[0];

    try {
        ois = new ObjectInputStream(socket.getInputStream());
        drinkar = (HashMap<String, ArrayList<String>>) (ois.readObject());
        System.out.println(drinkar);

        System.out.println(Arrays.toString(drinkar.keySet().toArray()));
        list = (String[]) (drinkar.keySet().toArray());

        for(int i = 0; i < list.length; i++){
            System.out.println(list);
        }


    } catch (ClassNotFoundException ex) {
        System.out.println(ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }
    return list;

}

Answer

Petr picture Petr · Aug 22, 2012

Use toArray(T[]) as:

String[] list = drinkar.keySet().toArray(new String[0]);

By giving an empty array as the argument, you tell toArray to create a new array of the same type for you that will be just of the correct size.


Just a note: If you can choose, it's usually more convenient (and safer) to work with collections such as ArrayList instead of arrays.