Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Object[] from a hashmap keyset to String[]?

Tags:

java

hashmap

Set<String> keys = mappings.keySet();
String[] keyArray = (String[]) keys.toArray();

String hashmapDetails = "";
for(int p=0; p < keyArray.length; p++){
    String[] details = keyArray[p].split("/");
    hashmapDetails += details[1];
    hashmapDetails += mappings.get(keyArray[p]);
    if (p != keyArray.length -1){
        hashmapDetails += ";";
    }
}

Pardon my lack of understanding but I'm trying to explore the usage of hashmaps. I understand that the toArray() returns an Object[]. However, is it not possible to type cast it to a String[]? As you can see in the codes, later, I need to go through an array and do some splitting and other String manipulation.

By doing this I got an error:

java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]

Any guidance on how I should tackle this is greatly appreciated. Thanks!

like image 804
lyk Avatar asked Apr 15 '13 18:04

lyk


People also ask

How do you convert the values of a HashMap to an array?

One way to convert is to use the constructor of the ArrayList. In order to do this, we can use the keySet() method present in the HashMap. This method returns the set containing all the keys of the hashmap.

How do you convert a map to a String?

Use Object#toString() . String string = map. toString();

What does HashMap keySet return?

The Java HashMap keySet() method returns a set view of all the keys present in entries of the hashmap.


2 Answers

You can't simply cast an Object[] array to a String[] array. You should instead use the generic version of toArray, which should work better:

String[] keyArray = keys.toArray(new String[keys.size()]);

Also note that you could simply iterate over the entrySet (that will save all the get calls) and use a StringBuilder for better string concatenation efficiency:

StringBuilder hashmapDetails = new StringBuilder();
for(Map.Entry<String, String> e : mappings.entrySet()) {
    String[] details = e.getKey().split("/");
    hashmapDetails += details[1];
    hashmapDetails += e.getValue();
    hashmapDetails += ";";
}

String result = hashmapDetails.substring(0, hashmapDetails.length() - 1);
like image 52
assylias Avatar answered Oct 02 '22 19:10

assylias


It is possible to cast keyset to String[]. Try this:

String[] keys = map.keySet().toArray(new String[0]);
like image 22
Adnan Avatar answered Oct 02 '22 19:10

Adnan